diff --git a/.gitattributes b/.gitattributes index 6c22559e188d87f662a8efa24c1e87e2266eff02..7e7f27b91fad93a838a4026eb34f90e59a9d7da5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -45,3 +45,4 @@ Mistral-7B-v0.1/full-checkpoint/ocdbt.process_0/d/5f96e30116e3c64eb48be0dcd852e2 Mistral-7B-v0.1/full-checkpoint/ocdbt.process_0/d/725ec5fffd1e19943ee3db876b61e4c9 filter=lfs diff=lfs merge=lfs -text Mistral-7B-v0.1/full-checkpoint/ocdbt.process_0/d/a1f1e882590e106a9ac95bce84cebce6 filter=lfs diff=lfs merge=lfs -text Mistral-7B-v0.1/full-checkpoint/ocdbt.process_0/d/ed87bb9cdcf4384203b288a71e45b5f4 filter=lfs diff=lfs merge=lfs -text +maxtext-setup/maxtext/assets/tokenizer.gemma filter=lfs diff=lfs merge=lfs -text diff --git a/maxtext-setup/maxtext/.github/CODEOWNERS b/maxtext-setup/maxtext/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..16e22b59f69359a45bfceacaa38286117a40cc7c --- /dev/null +++ b/maxtext-setup/maxtext/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Changes in this file should match with requiredReviewers in .github/workflows/AddLabel.yml +* @rwitten diff --git a/maxtext-setup/maxtext/.github/workflows/AddLabel.yml b/maxtext-setup/maxtext/.github/workflows/AddLabel.yml new file mode 100644 index 0000000000000000000000000000000000000000..a5f1033f2ea6dd30e505cb23d3c80117fb78fd25 --- /dev/null +++ b/maxtext-setup/maxtext/.github/workflows/AddLabel.yml @@ -0,0 +1,109 @@ +# Copyright 2023 Google LLC +# +# 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. + +name: Add Label + +on: + workflow_run: + workflows: [Unit Test, CodeQL] + types: + - completed + pull_request_review: + pull_request_review_comment: + workflow_dispatch: + +jobs: + AddPullReady: + permissions: + checks: read + pull-requests: write + runs-on: ubuntu-latest + + steps: + - uses: actions/github-script@v6 + with: + script: | + const owner = "google" + const repo = "maxtext" + let pull_number = -1 + if (context.payload.pull_request !== undefined) { + pull_number = context.payload.pull_request.number + } else if (context.payload.workflow_run !== undefined) { + if (context.payload.workflow_run.pull_requests.length === 0) { + console.log("This workflow is NOT running within a PR's context") + process.exit() + } + console.log(context.payload.workflow_run.pull_requests) + pull_number = context.payload.workflow_run.pull_requests[0].number + } else { + console.log("This workflow is running within an invalid context") + process.exit(1) + } + + // This list should match with CODEOWNERS + let requiredReviewers = { rwitten: "" } + const reviews = await github.rest.pulls.listReviews({ + owner, + repo, + pull_number, + }) + if (reviews.data.length === 0) { + console.log("Not adding pull ready because the PR is not approved yet") + process.exit() + } + for (const review of reviews.data) { + if (review.state === "APPROVED") { + delete requiredReviewers[review.user.login] + } + } + if (Object.keys(requiredReviewers).length !== 0) { + console.log("Not adding pull ready because the PR is not approved yet") + process.exit() + } + + const commits = await github.rest.pulls.listCommits({ + owner, + repo, + pull_number, + per_page: 100, + }) + // Check that the number of commits in the PR is 1. + if (commits.data.length !== 1) { + console.log("Not adding pull ready because the PR has more than one commit. Please squash your commits.") + process.exit(1) + } + const ref = commits.data.slice(-1)[0].sha + const checkRuns = await github.rest.checks.listForRef({ + owner, + repo, + ref, + }) + if (checkRuns.data.check_runs.length === 0) { + console.log("Not adding pull ready because no check runs are associated with the last commit: " + ref) + process.exit() + } + for (const checkRun of checkRuns.data.check_runs) { + if (checkRun.name.endsWith(context.job)) continue + if (checkRun.conclusion !== "success") { + console.log("Not adding pull ready because " + checkRun.name + " has not passed yet: " + checkRun.html_url) + process.exit() + } + } + console.log("Adding pull ready label because the PR is approved AND all the check runs have passed") + await github.rest.issues.addLabels({ + issue_number: pull_number, + labels: ["pull ready"], + owner, + repo, + }) diff --git a/maxtext-setup/maxtext/.github/workflows/UnitTests.yml b/maxtext-setup/maxtext/.github/workflows/UnitTests.yml new file mode 100644 index 0000000000000000000000000000000000000000..69117160ec6e7ad2dd11c4016f6d29de520b0790 --- /dev/null +++ b/maxtext-setup/maxtext/.github/workflows/UnitTests.yml @@ -0,0 +1,168 @@ +# Copyright 2023 Google LLC +# +# 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. + +# This workflow will install Python dependencies, run tests and lint with a variety of Python versions +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python + +name: Unit Test + +on: + pull_request: + push: + branches: [ "main" ] + workflow_dispatch: + schedule: + # Run the job every 2 hours + - cron: '0 */2 * * *' + +jobs: + cpu: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-20.04] + python-version: ['3.10'] + steps: + - uses: actions/checkout@v3 + - name: setup python + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install Dependencies + run: | + pip install pytype==2024.2.27 + pip install pylint + - name: Typecheck the code with pytype + run: | + pytype --jobs auto --disable import-error MaxText/ + - name: Analysing the code with pylint + run: | + pylint MaxText/ + + + # IF YOU MODIFY THIS, YOU SHOULD ALSO ADD CORRESPONDING MODICATIONS TO 'gpu' job + tpu: + strategy: + fail-fast: false + matrix: + device-type: ["v4-8"] + name: "TPU test (${{ matrix.device-type }})" + runs-on: ["self-hosted", "tpu", "${{ matrix.device-type }}"] + steps: + - uses: actions/checkout@v3 + - name: Cleanup old docker images + run: | + docker system prune --all --force + - name: Install dependencies + run: | + bash docker_build_dependency_image.sh + - name: Test gsutil installation + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'which gsutil >/dev/null 2>&1 || { echo >&2 "gsutil is required but not installed. Aborting"; exit 24;}' + - name: Test with pytest + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c 'cd MaxText;python3 -m pytest' + - name: Test train.py with c4 + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/train.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=2 enable_checkpointing=false' + - name: Test train.py with synthetic data + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/train.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=2 enable_checkpointing=false dataset_type=synthetic' + - name: Test train.py with per_device_batch_size < 1 + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/train.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=2 per_device_batch_size=0.25 ici_tensor_parallelism=4 enable_checkpointing=false' + - name: Test decode.py + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/decode.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=2 ici_tensor_parallelism=4 attention=dot_product enable_checkpointing=false max_target_length=128 per_device_batch_size=1' + - name: Test decode.py with per_device_batch_size < 1 + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/decode.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=2 ici_tensor_parallelism=4 attention=dot_product enable_checkpointing=false max_target_length=128 per_device_batch_size=.25' + - name: Test standalone_dataloader.py + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/standalone_dataloader.py MaxText/configs/base.yml run_name=standalone_dataloader_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=100 enable_checkpointing=false' + - name: Test standalone_checkpointer.py + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/standalone_checkpointer.py MaxText/configs/base.yml run_name=standalone_checkpointer_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=200 checkpoint_period=50 enable_checkpointing=True async_checkpointing=False' + - name: Test int8_training + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/train.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset quantization=int8 steps=2 enable_checkpointing=false' + - name: Test generate_param_only_checkpoint + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'bash end_to_end/test_generate_param_only_checkpoint.sh -r runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} -o gs://runner-maxtext-logs -d gs://maxtext-dataset -i 4' + - name: Test grain checkpoint determinism + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'bash end_to_end/test_checkpointing.sh runner gs://runner-maxtext-logs gs://maxtext-dataset False c4-array_record' + - name: Test checkpoint compatibility + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'bash end_to_end/test_checkpoint_compatibility.sh runner gs://runner-maxtext-logs gs://maxtext-dataset' + - name: Validate Pedagogical Example, Shmap_collective_matmul + run: | + docker run -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 pedagogical_examples/shmap_collective_matmul.py' + + # IF YOU MODIFY THIS, YOU SHOULD ALSO ADD CORRESPONDING MODICATIONS TO 'tpu' job + gpu: + strategy: + fail-fast: false + matrix: + device-type: ["a100-40gb-4"] + name: "GPU test (${{ matrix.device-type }})" + runs-on: ["self-hosted", "gpu", "${{ matrix.device-type }}"] + steps: + - uses: actions/checkout@v3 + - name: Cleanup old docker images + run: | + docker system prune --all --force + - name: Install dependencies + run: | + bash docker_build_dependency_image.sh DEVICE=gpu + - name: Test gsutil installation + run: | + docker run --runtime=nvidia --gpus all -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'which gsutil >/dev/null 2>&1 || { echo >&2 "gsutil is required but not installed. Aborting"; exit 24;}' + - name: Test with pytest + run: | + docker run -e XLA_PYTHON_CLIENT_MEM_FRACTION=0.65 -e TF_FORCE_GPU_ALLOW_GROWTH=true --shm-size=2g --runtime=nvidia --gpus all -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c 'cd MaxText;python3 -m pytest -m "not tpu"' + - name: Test train.py + run: | + docker run -e XLA_PYTHON_CLIENT_MEM_FRACTION=0.65 -e TF_FORCE_GPU_ALLOW_GROWTH=true --shm-size=2g --runtime=nvidia --gpus all -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/train.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=2 enable_checkpointing=false attention=dot_product' + - name: Test train.py with per_device_batch_size < 1 + run: | + docker run -e XLA_PYTHON_CLIENT_MEM_FRACTION=0.65 -e TF_FORCE_GPU_ALLOW_GROWTH=true --shm-size=2g --runtime=nvidia --gpus all -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/train.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=2 per_device_batch_size=0.25 ici_tensor_parallelism=4 enable_checkpointing=false attention=dot_product' + - name: Test int8_training + run: | + docker run -e XLA_PYTHON_CLIENT_MEM_FRACTION=0.65 -e TF_FORCE_GPU_ALLOW_GROWTH=true --shm-size=2g --runtime=nvidia --gpus all -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/train.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset quantization=int8 steps=2 enable_checkpointing=false attention=dot_product' + - name: Test decode.py + run: | + docker run -e XLA_PYTHON_CLIENT_MEM_FRACTION=0.65 -e TF_FORCE_GPU_ALLOW_GROWTH=true --shm-size=2g --runtime=nvidia --gpus all -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/decode.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=2 ici_tensor_parallelism=4 attention=dot_product enable_checkpointing=false max_target_length=128 per_device_batch_size=1' + - name: Test decode.py with per_device_batch_size < 1 + run: | + docker run -e XLA_PYTHON_CLIENT_MEM_FRACTION=0.65 -e TF_FORCE_GPU_ALLOW_GROWTH=true --shm-size=2g --runtime=nvidia --gpus all -v /home/runner/actions-runner/_work/maxtext/maxtext:/app --rm --privileged maxtext_base_image bash -c \ + 'python3 MaxText/decode.py MaxText/configs/base.yml run_name=runner_$(date +%Y-%m-%d-%H-%M)-${RANDOM} base_output_directory=gs://runner-maxtext-logs dataset_path=gs://maxtext-dataset steps=2 ici_tensor_parallelism=4 attention=dot_product enable_checkpointing=false max_target_length=128 per_device_batch_size=.25' diff --git a/maxtext-setup/maxtext/.github/workflows/UploadDockerImages.yml b/maxtext-setup/maxtext/.github/workflows/UploadDockerImages.yml new file mode 100644 index 0000000000000000000000000000000000000000..2ecbf76ccc9e8b8fdccddebaa0f0771fbd08c1fd --- /dev/null +++ b/maxtext-setup/maxtext/.github/workflows/UploadDockerImages.yml @@ -0,0 +1,53 @@ +# Copyright 2023 Google LLC +# +# 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. + +# This workflow will install Python dependencies, run tests and lint with a variety of Python versions +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python + +name: Build Images + +on: + schedule: + # Run the job daily at 7PM PST (3AM UTC) + - cron: '0 3 * * *' + +jobs: + tpu: + strategy: + fail-fast: false + matrix: + device-type: ["v4-8"] + runs-on: ["self-hosted", "tpu", "${{ matrix.device-type }}"] + steps: + - uses: actions/checkout@v3 + - name: build jax stable image + run : | + bash .github/workflows/build_and_upload_images.sh CLOUD_IMAGE_NAME=maxtext_jax_stable MODE=stable DEVICE=tpu PROJECT=tpu-prod-env-multipod LOCAL_IMAGE_NAME=maxtext_jax_stable + - name: build jax nightly image + run : | + bash .github/workflows/build_and_upload_images.sh CLOUD_IMAGE_NAME=maxtext_jax_nightly MODE=nightly DEVICE=tpu PROJECT=tpu-prod-env-multipod LOCAL_IMAGE_NAME=maxtext_jax_nightly + gpu: + strategy: + fail-fast: false + matrix: + device-type: ["a100-40gb-4"] + runs-on: ["self-hosted", "gpu", "${{ matrix.device-type }}"] + steps: + - uses: actions/checkout@v3 + - name: build jax stable image + run : | + bash .github/workflows/build_and_upload_images.sh CLOUD_IMAGE_NAME=maxtext_gpu_jax_stable MODE=stable DEVICE=gpu PROJECT=tpu-prod-env-multipod LOCAL_IMAGE_NAME=maxtext_gpu_local_jax_stable + - name: build jax nightly image + run : | + bash .github/workflows/build_and_upload_images.sh CLOUD_IMAGE_NAME=maxtext_gpu_jax_nightly MODE=nightly DEVICE=gpu PROJECT=tpu-prod-env-multipod LOCAL_IMAGE_NAME=maxtext_gpu_local_jax_nightly \ No newline at end of file diff --git a/maxtext-setup/maxtext/.github/workflows/build_and_upload_images.sh b/maxtext-setup/maxtext/.github/workflows/build_and_upload_images.sh new file mode 100644 index 0000000000000000000000000000000000000000..226a35687d2769b694eea2d2bef223fe6ad731f5 --- /dev/null +++ b/maxtext-setup/maxtext/.github/workflows/build_and_upload_images.sh @@ -0,0 +1,58 @@ +#!/bin/bash + +# Copyright 2023 Google LLC +# +# 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. + +# This script builds and uploads two images - one with only dependencies, the other also has a code snapshot. +# These images are tagged in GCR with both "latest" and date in format YYYY-MM-DD via $(date +%Y-%m-%d) + +# This script wraps several steps meant for the github runners to push nightly images. +# If you want to create and push your own images you should instead use docker_build_dependency_image and +# docker_upload_runner in the maxtext root directory. + +# Example command: +# bash build_and_upload_images.sh PROJECT= MODE=stable DEVICE=tpu CLOUD_IMAGE_NAME=${USER}_runner + + +export LOCAL_IMAGE_NAME=maxtext_base_image + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" + echo "$KEY"="$VALUE" +done + +if [[ ! -v CLOUD_IMAGE_NAME ]] || [[ ! -v PROJECT ]] || [[ ! -v MODE ]] || [[ ! -v DEVICE ]]; then + echo "You must set CLOUD_IMAGE_NAME, PROJECT, MODE, and DEVICE" + exit 1 +fi + +bash docker_build_dependency_image.sh LOCAL_IMAGE_NAME=$LOCAL_IMAGE_NAME MODE=$MODE DEVICE=$DEVICE +gcloud auth configure-docker --quiet +image_date=$(date +%Y-%m-%d) + +# Upload only dependencies image +dependency_image_name=${CLOUD_IMAGE_NAME}_dependencies +docker tag ${LOCAL_IMAGE_NAME} gcr.io/$PROJECT/${dependency_image_name}:latest +docker push gcr.io/$PROJECT/${dependency_image_name}:latest +docker tag ${LOCAL_IMAGE_NAME} gcr.io/$PROJECT/${dependency_image_name}:${image_date} +docker push gcr.io/$PROJECT/${dependency_image_name}:${image_date} + +# Build then upload "dependencies + code" image +docker build --build-arg BASEIMAGE=${LOCAL_IMAGE_NAME} -f ./maxtext_runner.Dockerfile -t ${LOCAL_IMAGE_NAME}_runner . +docker tag ${LOCAL_IMAGE_NAME}_runner gcr.io/$PROJECT/${CLOUD_IMAGE_NAME}:latest +docker push gcr.io/$PROJECT/${CLOUD_IMAGE_NAME}:latest +docker tag ${LOCAL_IMAGE_NAME}_runner gcr.io/$PROJECT/${CLOUD_IMAGE_NAME}:${image_date} +docker push gcr.io/$PROJECT/${CLOUD_IMAGE_NAME}:${image_date} \ No newline at end of file diff --git a/maxtext-setup/maxtext/.github/workflows/utils/setup_runner.sh b/maxtext-setup/maxtext/.github/workflows/utils/setup_runner.sh new file mode 100644 index 0000000000000000000000000000000000000000..c320a1589dc01a10c093821e9ae9d246d5f672a3 --- /dev/null +++ b/maxtext-setup/maxtext/.github/workflows/utils/setup_runner.sh @@ -0,0 +1,77 @@ +#!/bin/bash + +# Copyright 2022 The JAX Authors. +# +# 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. + +# Heavily influenced by +# https://github.com/openxla/iree/tree/main/build_tools/github_actions/runner/config + +# This file sets up a tpu vm to be used as a github runner for testing. +# It creates a user runner without sudo permissions to +# run the config file and authenticate to github + + +set -eux + +if [ "$#" -ne 4 ]; then + echo "Usage: setup_runner.sh " +fi + +runner_name="$1" +runner_tags="$2" +runner_token="$3" +repo_url="$4" + + +# Create `runner` user. This user won't have sudo access unless you ssh into the +# GCP VM as `runner` using gcloud. Don't do that! +sudo useradd runner -m +ORIGIN_USER=${USER} +# Find the latest actions-runner download. The runner will automatically update +# itself when new versions are released. Github requires that all self-hosted +# runners are updated to the latest version within 30 days of release +# (https://docs.github.com/en/actions/hosting-your-own-runners/autoscaling-with-self-hosted-runners#controlling-runner-software-updates-on-self-hosted-runners). +# Example URL: +# https://github.com/actions/runner/releases/download/v2.298.2/actions-runner-linux-x64-2.298.2.tar.gz +actions_runner_download_regexp='https://github.com/actions/runner/releases/'\ +'download/v[0-9.]\+/actions-runner-linux-x64-[0-9.]\+\.tar\.gz' +# Use `head -n 1` because there are multiple instances of the same URL +actions_runner_download=$( + curl -s -X GET 'https://api.github.com/repos/actions/runner/releases/latest' | + grep -o "${actions_runner_download_regexp}" | + head -n 1) +echo "actions_runner_download: ${actions_runner_download}" + +# Run the rest of the setup as `runner`. +# +# Note that env vars in the heredoc will be expanded according to the _calling_ +# environment, not the `runner` environment we're creating -- it acts like a +# double-quoted string. This is how variables like $runner_name are inserted +# without using sudo -E (which would cause the current environment to be +# inherited). This also means we must be careful to escape any variables that +# we'd like to evaluate in the `runner` environment, e.g. $HOME. +sudo -i -u runner bash -ex < to see your current agreements or to +sign a new one. + +### Review our Community Guidelines + +This project follows +[Google's Open Source Community Guidelines](https://opensource.google/conduct/). + +## Contribution process + +### Code Reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. \ No newline at end of file diff --git a/maxtext-setup/maxtext/LICENSE b/maxtext-setup/maxtext/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/maxtext-setup/maxtext/LICENSE @@ -0,0 +1,201 @@ + 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/maxtext-setup/maxtext/MaxText/__init__.py b/maxtext-setup/maxtext/MaxText/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..83f918e62e17b86823d2c7a9c63bf56a33bdb4f8 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/__init__.py @@ -0,0 +1,15 @@ +""" + Copyright 2023 Google LLC + + 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. + """ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/accelerator_to_spec_map.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/accelerator_to_spec_map.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3ec6ec069185ec521e1707bbd61209e125f3d49 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/accelerator_to_spec_map.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/checkpointing.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/checkpointing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a33b8b41afac4a3501f054be115d652cf8810c21 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/checkpointing.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/common_types.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/common_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc40653041acab2b2214cb8c79595533045b429f Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/common_types.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/max_logging.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/max_logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e824d590f268c5511978039f83abab687e027ba9 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/max_logging.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/max_utils.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/max_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56975144f4cda54e22995a3eb152a7a2c85e287b Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/max_utils.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/maxtext_utils.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/maxtext_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5cdf6832b420a962be6dda97c7c957a7cba288f Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/maxtext_utils.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/multihost_dataloading.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/multihost_dataloading.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dee09f2c87155e9c5c960a545b58eece4de0eda5 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/multihost_dataloading.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/optimizers.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/optimizers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..348bb9fc0e26c978cc563dbecb5cc87ef8516ed7 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/optimizers.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/pyconfig.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/pyconfig.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5c263f43ea7bcd4cbcf6b473d6f9c6fc2609728 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/pyconfig.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/sequence_packing.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/sequence_packing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88379ecefa634d184614f69d19cb4cd141f67686 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/sequence_packing.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/tokenizer.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/tokenizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2bf66552fa11a699f1670a75a001e42a51b1513 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/tokenizer.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/__pycache__/train.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/__pycache__/train.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f42581d3f5d18019fed67c6a0d337abd04f4791 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/__pycache__/train.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/accelerator_to_spec_map.py b/maxtext-setup/maxtext/MaxText/accelerator_to_spec_map.py new file mode 100644 index 0000000000000000000000000000000000000000..fa6b64d0a9d5854815617350887cfb2b340c6d2b --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/accelerator_to_spec_map.py @@ -0,0 +1,379 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Static map of TPU names such as v4-8 to properties such as chip layout.""" + +""" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +IF YOU MODIFY THIS FILE YOU SHOULD ALSO ADD CORRESPONDING MODICATIONS TO +UserFacingNameToSystemCharacteristics in xpk/xpk.py !!!!! """ + +from dataclasses import dataclass + +@dataclass +class SystemCharacteristics: + platform: str + topology_name: str + chip_config_name: str # 'megacore' or 'default' + chips_per_host_bounds: tuple + devices_per_slice: int + +UserFacingNameToSystemCharacteristics = { + # v5e + 'v5e-16': SystemCharacteristics( + 'tpu', 'v5e:4x4', 'default', (2, 2, 1), 16 + ), + 'v5e-32': SystemCharacteristics( + 'tpu', 'v5e:4x8', 'default', (2, 2, 1), 32 + ), + 'v5e-64': SystemCharacteristics( + 'tpu', 'v5e:8x8', 'default', (2, 2, 1), 64 + ), + 'v5e-128': SystemCharacteristics( + 'tpu', 'v5e:8x16', 'default', (2, 2, 1), 128 + ), + 'v5e-256': SystemCharacteristics( + 'tpu', 'v5e:16x16', 'default', (2, 2, 1), 256 + ), + # v4 + 'v4-8': SystemCharacteristics( + 'tpu', 'v4:2x2x1', 'megacore', (2, 2, 1), 4 + ), + 'v4-16': SystemCharacteristics( + 'tpu', 'v4:2x2x2', 'megacore', (2, 2, 1), 8 + ), + 'v4-32': SystemCharacteristics( + 'tpu', 'v4:2x2x4', 'megacore', (2, 2, 1), 16 + ), + 'v4-64': SystemCharacteristics( + 'tpu', 'v4:2x4x4', 'megacore', (2, 2, 1), 32 + ), + 'v4-128': SystemCharacteristics( + 'tpu', 'v4:4x4x4', 'megacore', (2, 2, 1), 64 + ), + 'v4-256': SystemCharacteristics( + 'tpu', 'v4:4x4x8', 'megacore', (2, 2, 1), 128 + ), + 'v4-384': SystemCharacteristics( + 'tpu', 'v4:4x4x12', 'megacore', (2, 2, 1), 192 + ), + 'v4-512': SystemCharacteristics( + 'tpu', 'v4:4x8x8', 'megacore', (2, 2, 1), 256 + ), + 'v4-1024': SystemCharacteristics( + 'tpu', 'v4:8x8x8', 'megacore', (2, 2, 1), 512 + ), + 'v4-1536': SystemCharacteristics( + 'tpu', 'v4:8x8x12','megacore', (2, 2, 1), 768 + ), + 'v4-2048': SystemCharacteristics( + 'tpu', 'v4:8x8x16','megacore', (2, 2, 1), 1024 + ), + 'v4-4096': SystemCharacteristics( + 'tpu', 'v4:8x16x16', 'megacore', (2, 2, 1), 2048 + ), + # v5p + 'v5p-8': SystemCharacteristics( + 'tpu', 'v5:2x2x1', 'megacore', (2, 2, 1), 4 + ), + 'v5p-16': SystemCharacteristics( + 'tpu', 'v5:2x2x2', 'megacore', (2, 2, 1), 8 + ), + 'v5p-32': SystemCharacteristics( + 'tpu', 'v5:2x2x4', 'megacore', (2, 2, 1), 16 + ), + 'v5p-64': SystemCharacteristics( + 'tpu', 'v5:2x4x4', 'megacore', (2, 2, 1), 32 + ), + 'v5p-128': SystemCharacteristics( + 'tpu', 'v5:4x4x4', 'megacore', (2, 2, 1), 64 + ), + 'v5p-256': SystemCharacteristics( + 'tpu', 'v5:4x4x8', 'megacore', (2, 2, 1), 128 + ), + 'v5p-384': SystemCharacteristics( + 'tpu', 'v5:4x4x12', 'megacore', (2, 2, 1), 192 + ), + 'v5p-512': SystemCharacteristics( + 'tpu', 'v5:4x8x8', 'megacore', (2, 2, 1), 256 + ), + 'v5p-640': SystemCharacteristics( + 'tpu', 'v5:4x4x20', 'megacore', (2, 2, 1), 320 + ), + 'v5p-768': SystemCharacteristics( + 'tpu', 'v5:4x8x12', 'megacore', (2, 2, 1), 384 + ), + 'v5p-896': SystemCharacteristics( + 'tpu', 'v5:4x4x28', 'megacore', (2, 2, 1), 448 + ), + 'v5p-1024': SystemCharacteristics( + 'tpu', 'v5:8x8x8', 'megacore', (2, 2, 1), 512 + ), + 'v5p-1152': SystemCharacteristics( + 'tpu', 'v5:4x12x12', 'megacore', (2, 2, 1), 576 + ), + 'v5p-1280': SystemCharacteristics( + 'tpu', 'v5:4x8x20', 'megacore', (2, 2, 1), 640 + ), + 'v5p-1408': SystemCharacteristics( + 'tpu', 'v5:4x4x44', 'megacore', (2, 2, 1), 704 + ), + 'v5p-1536': SystemCharacteristics( + 'tpu', 'v5:8x8x12', 'megacore', (2, 2, 1), 768 + ), + 'v5p-1664': SystemCharacteristics( + 'tpu', 'v5:4x4x52', 'megacore', (2, 2, 1), 832 + ), + 'v5p-1792': SystemCharacteristics( + 'tpu', 'v5:4x8x28', 'megacore', (2, 2, 1), 896 + ), + 'v5p-1920': SystemCharacteristics( + 'tpu', 'v5:4x12x20', 'megacore', (2, 2, 1), 960 + ), + 'v5p-2048': SystemCharacteristics( + 'tpu', 'v5:8x8x16', 'megacore', (2, 2, 1), 1024 + ), + 'v5p-2176': SystemCharacteristics( + 'tpu', 'v5:4x4x68', 'megacore', (2, 2, 1), 1088 + ), + 'v5p-2304': SystemCharacteristics( + 'tpu', 'v5:8x12x12', 'megacore', (2, 2, 1), 1152 + ), + 'v5p-2432': SystemCharacteristics( + 'tpu', 'v5:4x4x76', 'megacore', (2, 2, 1), 1216 + ), + 'v5p-2560': SystemCharacteristics( + 'tpu', 'v5:8x8x20', 'megacore', (2, 2, 1), 1280 + ), + 'v5p-2688': SystemCharacteristics( + 'tpu', 'v5:4x12x28', 'megacore', (2, 2, 1), 1344 + ), + 'v5p-2816': SystemCharacteristics( + 'tpu', 'v5:4x8x44', 'megacore', (2, 2, 1), 1408 + ), + 'v5p-2944': SystemCharacteristics( + 'tpu', 'v5:4x4x92', 'megacore', (2, 2, 1), 1472 + ), + 'v5p-3072': SystemCharacteristics( + 'tpu', 'v5:8x12x16', 'megacore', (2, 2, 1), 1536 + ), + 'v5p-3200': SystemCharacteristics( + 'tpu', 'v5:4x20x20', 'megacore', (2, 2, 1), 1600 + ), + 'v5p-3328': SystemCharacteristics( + 'tpu', 'v5:4x8x52', 'megacore', (2, 2, 1), 1664 + ), + 'v5p-3456': SystemCharacteristics( + 'tpu', 'v5:12x12x12', 'megacore', (2, 2, 1), 1728 + ), + 'v5p-3584': SystemCharacteristics( + 'tpu', 'v5:8x8x28', 'megacore', (2, 2, 1), 1792 + ), + 'v5p-3712': SystemCharacteristics( + 'tpu', 'v5:4x4x116', 'megacore', (2, 2, 1), 1856 + ), + 'v5p-3840': SystemCharacteristics( + 'tpu', 'v5:8x12x20', 'megacore', (2, 2, 1), 1920 + ), + 'v5p-3968': SystemCharacteristics( + 'tpu', 'v5:4x4x124', 'megacore', (2, 2, 1), 1984 + ), + 'v5p-4096': SystemCharacteristics( + 'tpu', 'v5:8x16x16', 'megacore', (2, 2, 1), 2048 + ), + 'v5p-4224': SystemCharacteristics( + 'tpu', 'v5:4x12x44', 'megacore', (2, 2, 1), 2112 + ), + 'v5p-4352': SystemCharacteristics( + 'tpu', 'v5:4x8x68', 'megacore', (2, 2, 1), 2176 + ), + 'v5p-4480': SystemCharacteristics( + 'tpu', 'v5:4x20x28', 'megacore', (2, 2, 1), 2240 + ), + 'v5p-4608': SystemCharacteristics( + 'tpu', 'v5:12x12x16', 'megacore', (2, 2, 1), 2304 + ), + 'v5p-4736': SystemCharacteristics( + 'tpu', 'v5:4x4x148', 'megacore', (2, 2, 1), 2368 + ), + 'v5p-4864': SystemCharacteristics( + 'tpu', 'v5:4x8x76', 'megacore', (2, 2, 1), 2432 + ), + 'v5p-4992': SystemCharacteristics( + 'tpu', 'v5:4x12x52', 'megacore', (2, 2, 1), 2496 + ), + 'v5p-5120': SystemCharacteristics( + 'tpu', 'v5:8x16x20', 'megacore', (2, 2, 1), 2560 + ), + 'v5p-5248': SystemCharacteristics( + 'tpu', 'v5:4x4x164', 'megacore', (2, 2, 1), 2624 + ), + 'v5p-5376': SystemCharacteristics( + 'tpu', 'v5:8x12x28', 'megacore', (2, 2, 1), 2688 + ), + 'v5p-5504': SystemCharacteristics( + 'tpu', 'v5:4x4x172', 'megacore', (2, 2, 1), 2752 + ), + 'v5p-5632': SystemCharacteristics( + 'tpu', 'v5:8x8x44', 'megacore', (2, 2, 1), 2816 + ), + 'v5p-5760': SystemCharacteristics( + 'tpu', 'v5:12x12x20', 'megacore', (2, 2, 1), 2880 + ), + 'v5p-5888': SystemCharacteristics( + 'tpu', 'v5:4x8x92', 'megacore', (2, 2, 1), 2944 + ), + 'v5p-6016': SystemCharacteristics( + 'tpu', 'v5:4x4x188', 'megacore', (2, 2, 1), 3008 + ), + 'v5p-6144': SystemCharacteristics( + 'tpu', 'v5:12x16x16', 'megacore', (2, 2, 1), 3072 + ), + 'v5p-6272': SystemCharacteristics( + 'tpu', 'v5:4x28x28', 'megacore', (2, 2, 1), 3136 + ), + 'v5p-6400': SystemCharacteristics( + 'tpu', 'v5:8x20x20', 'megacore', (2, 2, 1), 3200 + ), + 'v5p-6528': SystemCharacteristics( + 'tpu', 'v5:4x12x68', 'megacore', (2, 2, 1), 3264 + ), + 'v5p-6656': SystemCharacteristics( + 'tpu', 'v5:8x8x52', 'megacore', (2, 2, 1), 3328 + ), + 'v5p-6784': SystemCharacteristics( + 'tpu', 'v5:4x4x212', 'megacore', (2, 2, 1), 3392 + ), + 'v5p-6912': SystemCharacteristics( + 'tpu', 'v5:12x12x24', 'megacore', (2, 2, 1), 3456 + ), + 'v5p-7040': SystemCharacteristics( + 'tpu', 'v5:4x20x44', 'megacore', (2, 2, 1), 3520 + ), + 'v5p-7168': SystemCharacteristics( + 'tpu', 'v5:8x16x28', 'megacore', (2, 2, 1), 3584 + ), + 'v5p-7296': SystemCharacteristics( + 'tpu', 'v5:4x12x76', 'megacore', (2, 2, 1), 3648 + ), + 'v5p-7424': SystemCharacteristics( + 'tpu', 'v5:4x8x116', 'megacore', (2, 2, 1), 3712 + ), + 'v5p-7552': SystemCharacteristics( + 'tpu', 'v5:4x4x236', 'megacore', (2, 2, 1), 3776 + ), + 'v5p-7680': SystemCharacteristics( + 'tpu', 'v5:12x16x20', 'megacore', (2, 2, 1), 3840 + ), + 'v5p-7808': SystemCharacteristics( + 'tpu', 'v5:4x4x244', 'megacore', (2, 2, 1), 3904 + ), + 'v5p-7936': SystemCharacteristics( + 'tpu', 'v5:4x8x124', 'megacore', (2, 2, 1), 3968 + ), + 'v5p-8064': SystemCharacteristics( + 'tpu', 'v5:12x12x28', 'megacore', (2, 2, 1), 4032 + ), + 'v5p-8192': SystemCharacteristics( + 'tpu', 'v5:16x16x16', 'megacore', (2, 2, 1), 4096 + ), + 'v5p-8320': SystemCharacteristics( + 'tpu', 'v5:4x20x52', 'megacore', (2, 2, 1), 4160 + ), + 'v5p-8448': SystemCharacteristics( + 'tpu', 'v5:8x12x44', 'megacore', (2, 2, 1), 4224 + ), + 'v5p-8704': SystemCharacteristics( + 'tpu', 'v5:8x8x68', 'megacore', (2, 2, 1), 4352 + ), + 'v5p-8832': SystemCharacteristics( + 'tpu', 'v5:4x12x92', 'megacore', (2, 2, 1), 4416 + ), + 'v5p-8960': SystemCharacteristics( + 'tpu', 'v5:8x20x28', 'megacore', (2, 2, 1), 4480 + ), + 'v5p-9216': SystemCharacteristics( + 'tpu', 'v5:12x16x24', 'megacore', (2, 2, 1), 4608 + ), + 'v5p-9472': SystemCharacteristics( + 'tpu', 'v5:4x8x148', 'megacore', (2, 2, 1), 4736 + ), + 'v5p-9600': SystemCharacteristics( + 'tpu', 'v5:12x20x20', 'megacore', (2, 2, 1), 4800 + ), + 'v5p-9728': SystemCharacteristics( + 'tpu', 'v5:8x8x76', 'megacore', (2, 2, 1), 4864 + ), + 'v5p-9856': SystemCharacteristics( + 'tpu', 'v5:4x28x44', 'megacore', (2, 2, 1), 4928 + ), + 'v5p-9984': SystemCharacteristics( + 'tpu', 'v5:8x12x52', 'megacore', (2, 2, 1), 4992 + ), + 'v5p-10240': SystemCharacteristics( + 'tpu', 'v5:16x16x20', 'megacore', (2, 2, 1), 5120 + ), + 'v5p-10368': SystemCharacteristics( + 'tpu', 'v5:12x12x36', 'megacore', (2, 2, 1), 5184 + ), + 'v5p-10496': SystemCharacteristics( + 'tpu', 'v5:4x8x164', 'megacore', (2, 2, 1), 5248 + ), + 'v5p-10752': SystemCharacteristics( + 'tpu', 'v5:12x16x28', 'megacore', (2, 2, 1), 5376 + ), + 'v5p-10880': SystemCharacteristics( + 'tpu', 'v5:4x20x68', 'megacore', (2, 2, 1), 5440 + ), + 'v5p-11008': SystemCharacteristics( + 'tpu', 'v5:4x8x172', 'megacore', (2, 2, 1), 5504 + ), + 'v5p-11136': SystemCharacteristics( + 'tpu', 'v5:4x12x116', 'megacore', (2, 2, 1), 5568 + ), + 'v5p-11264': SystemCharacteristics( + 'tpu', 'v5:8x16x44', 'megacore', (2, 2, 1), 5632 + ), + 'v5p-11520': SystemCharacteristics( + 'tpu', 'v5:12x20x24', 'megacore', (2, 2, 1), 5760 + ), + 'v5p-11648': SystemCharacteristics( + 'tpu', 'v5:4x28x52', 'megacore', (2, 2, 1), 5824 + ), + 'v5p-11776': SystemCharacteristics( + 'tpu', 'v5:8x8x92', 'megacore', (2, 2, 1), 5888 + ), + 'v5p-11904': SystemCharacteristics( + 'tpu', 'v5:4x12x124', 'megacore', (2, 2, 1), 5952 + ), + 'v5p-12032': SystemCharacteristics( + 'tpu', 'v5:4x8x188', 'megacore', (2, 2, 1), 6016 + ), + 'v5p-12160': SystemCharacteristics( + 'tpu', 'v5:4x20x76', 'megacore', (2, 2, 1), 6080 + ), + 'v5p-12288': SystemCharacteristics( + 'tpu', 'v5:16x16x24', 'megacore', (2, 2, 1), 6144 + ), + 'v5p-13824': SystemCharacteristics( + 'tpu', 'v5:12x24x24', 'megacore', (2, 2, 1), 6912 + ), + 'v5p-17920': SystemCharacteristics( + 'tpu', 'v5:16x20x28', 'megacore', (2, 2, 1), 8960 + ), +} + +def get_system_characteristics(user_facing_name): + return UserFacingNameToSystemCharacteristics.get(user_facing_name) diff --git a/maxtext-setup/maxtext/MaxText/checkpointing.py b/maxtext-setup/maxtext/MaxText/checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..162f371fccf6c6c1c09183640833dc21abdec472 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/checkpointing.py @@ -0,0 +1,195 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Create an Orbax CheckpointManager with specified (Async or not) Checkpointer.""" + +from typing import Optional, Union +from etils import epath +from orbax.checkpoint.checkpoint_manager import CheckpointManager, CheckpointManagerOptions +import jax +import numpy as np +import orbax.checkpoint +import grain.python as grain + +import max_logging +from multihost_dataloading import MultiHostDataLoadIterator +from flax.training import train_state + +def create_orbax_checkpoint_manager( + checkpoint_dir: str, + enable_checkpointing: bool, + use_async: bool, + save_interval_steps: int, + dataset_type: Optional[str] = 'c4' +): + """Returns specified Orbax (async or not) CheckpointManager or None if checkpointing is disabled.""" + if not enable_checkpointing: + max_logging.log("Checkpointing disabled, not creating checkpoint manager.") + return None + max_logging.log("Creating checkpoint manager...") + p = epath.Path(checkpoint_dir) + + if dataset_type=='c4-array_record': + item_names = ('items', 'iter') + else: + item_names = ('items',) + + mngr = CheckpointManager( + p, + item_names = item_names, + options = CheckpointManagerOptions( + create=True, + save_interval_steps=save_interval_steps, + enable_async_checkpointing=use_async, + ) + ) + max_logging.log("Checkpoint manager created!") + return mngr + + +def _find_idx(array: np.ndarray, replica_axis_idx: int): + """Returns the index along given dimension that the current host belongs to.""" + idx = None + for idx, val in np.ndenumerate(array): + if val.process_index == jax.process_index(): + break + return idx[replica_axis_idx] + + +def _replica_devices(device_array: np.ndarray, replica_axis_idx: int): + """Returns the devices from the replica that current host belongs to. + + Replicas are assumed to be restricted to the first axis. + + Args: + device_array: devices of the mesh that can be obtained by mesh.devices() + replica_axis_idx: axis dimension along which replica is taken + + Returns: + devices inside the replica that current host is in + """ + idx = _find_idx(device_array, replica_axis_idx) + replica_result = np.take(device_array, + idx, + axis=replica_axis_idx) + return np.expand_dims(replica_result, axis=replica_axis_idx) + + +def load_state_if_possible(checkpoint_manager: CheckpointManager, + data_iterator: Union[MultiHostDataLoadIterator, None], + load_parameters_from_path: str, + load_full_state_from_path: str, + abstract_unboxed_pre_state: train_state.TrainState, + enable_single_replica_ckpt_restoring: Optional[bool] = False, + dataset_type: Optional[str] = 'c4'): + """Loads TrainState as possible from the inputs. + + Args: + checkpoint_manager: if the checkpoint_manager has a valid checkpoint, return + that TrainState. This enables a full reload of a run in progress. + load_parameters_from_path: if there is no checkpoint in the checkpoint manager, + load parameters from a parameter only checkpoint at this path. + load_full_state_from_path: if there is no checkpoint in the checkpoint manager, + load full state from a full state checkpoint at this path. + abstract_unboxed_pre_state: an unboxed, abstract TrainState that Orbax + matches type against. + enable_single_replica_ckpt_restoring: bool flag for restoring checkpoitn + with SingleReplicaArrayHandler + + Returns: + A tuple of (train_state, train_state_params) where full_train_state captures + a full reload and train_state_params just the params for a partial reload. + At most one will be non-None. Both can be None if neither checkpoint is + set. + """ + + if checkpoint_manager is not None: + max_logging.log("checkpoint manager exists so trying to load this run's existing checkpoint") + + latest_step = checkpoint_manager.latest_step() + if latest_step is not None: + max_logging.log(f"restoring from this run's directory latest step \ + {latest_step}") + + def map_to_pspec(data): + pspec = data.sharding.spec + mesh = data.sharding.mesh + if not enable_single_replica_ckpt_restoring: + return orbax.checkpoint.type_handlers.ArrayRestoreArgs(mesh=mesh, mesh_axes=pspec) + orbax.checkpoint.type_handlers.register_type_handler( + jax.Array, + orbax.checkpoint.type_handlers.SingleReplicaArrayHandler(), + override=True) + orbax.checkpoint.type_handlers.register_type_handler( + jax.Array, + orbax.checkpoint.type_handlers.SingleReplicaArrayHandler(), + override=True) + replica_axis_index = 0 # for maxtext data is the first dimension + replica_devices = _replica_devices(mesh.devices, replica_axis_index) + replica_mesh = jax.sharding.Mesh(replica_devices, mesh.axis_names) + single_replica_sharding = jax.sharding.NamedSharding(replica_mesh, pspec) + return orbax.checkpoint.type_handlers.SingleReplicaArrayRestoreArgs( + sharding=jax.sharding.NamedSharding(mesh, pspec), + single_replica_sharding=single_replica_sharding, + replica_axis_index=replica_axis_index, + global_shape=data.shape, + dtype=data.dtype, + ) + + restore_args = jax.tree_util.tree_map(map_to_pspec, + abstract_unboxed_pre_state, + ) + if dataset_type == 'c4-array_record' and data_iterator is not None: + return checkpoint_manager.restore( + latest_step, + args=orbax.checkpoint.args.Composite( + items=orbax.checkpoint.args.PyTreeRestore( + item=abstract_unboxed_pre_state, + restore_args=restore_args), + iter=grain.PyGrainCheckpointRestore(data_iterator.local_iterator)) + ), None + else: + return ( + checkpoint_manager.restore( + latest_step, + args=orbax.checkpoint.args.Composite( + items=orbax.checkpoint.args.PyTreeRestore( + item=abstract_unboxed_pre_state, + restore_args=restore_args) + ), + ), + None) + + if load_parameters_from_path != "": + max_logging.log(f"restoring params from {load_parameters_from_path=}") + p = epath.Path(load_parameters_from_path) + ckptr = orbax.checkpoint.PyTreeCheckpointer() + restore_args = orbax.checkpoint.checkpoint_utils.construct_restore_args(abstract_unboxed_pre_state.params) + restored = ckptr.restore(p, item = {'params': abstract_unboxed_pre_state.params}, transforms={}, + restore_args = {'params': restore_args}) + + return None, restored['params'] + + elif load_full_state_from_path != "": + max_logging.log(f"restoring full state from {load_full_state_from_path=}") + p = epath.Path(load_full_state_from_path) + ckptr = orbax.checkpoint.StandardCheckpointer() + restored = ckptr.restore(p, args=orbax.checkpoint.args.StandardRestore(abstract_unboxed_pre_state)) + return {'items': restored}, None + + else: + max_logging.log("No existing checkpoints found, not restoring checkpoint.") + return None, None diff --git a/maxtext-setup/maxtext/MaxText/common_types.py b/maxtext-setup/maxtext/MaxText/common_types.py new file mode 100644 index 0000000000000000000000000000000000000000..a2e0f389b840f7b7210fce7253c0212a5bfe0398 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/common_types.py @@ -0,0 +1,44 @@ +# Copyright 2023 Google LLC +# +# 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. + +"""Common types.""" + +from typing import Any, Sequence + +from flax.linen import partitioning +import jax +import jax.numpy as jnp + +Config = Any + +Array = jnp.ndarray +PRNGKey = jnp.ndarray +DType = jnp.dtype +Shape = Sequence[int] + +Mesh = jax.sharding.Mesh +ScanIn = partitioning.ScanIn + +AxisNames = tuple[str, ...] + +BATCH = 'activation_batch' +LENGTH = 'activation_length' +HEAD = 'activation_heads' +D_KV = 'activation_kv' + +MODEL_MODE_AUTOREGRESSIVE = 'autoregressive' +MODEL_MODE_PREFILL = 'prefill' +MODEL_MODE_TRAIN = 'train' + +DECODING_ACTIVE_SEQUENCE_INDICATOR = 1 diff --git a/maxtext-setup/maxtext/MaxText/configs/README.md b/maxtext-setup/maxtext/MaxText/configs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4ca6557ed740170f9fb292d29f6d51e8f59426b2 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/README.md @@ -0,0 +1,77 @@ + + +# High Performance Model Configs +This directory contains high performance model configurations for different generations of TPU hardware. + +These configurations do 3 things: +* Sets various XLA compiler flags as `LIBTPU_INIT_ARGS` to optimize runtime performance. +* Runs [rto_setup.sh](https://github.com/google/maxtext/blob/main/rto_setup.sh) to optimize communication protocols for network performance. +(This only needs to be run once on each worker) +* Runs [train.py](https://github.com/google/maxtext/blob/main/MaxText/train.py) with specific hyper-parameters (batch size, etc.) + + +## Reproduction Instructions + +### Create a custom MTU network +1. Create a custom MTU network to optimize network performance and give it firewall rules. If you are unable to complete this step, you may skip it. This step is not necessary, and is only for improving performance when running on a Multislice setup. + + Create a network with an MTU of 8896 bytes and set up firewall rules. (Creating a network requires `compute.networks.create` permission in your project) + ``` + gcloud compute networks create mtu9k --mtu=8896 --project=${PROJECT} --subnet-mode=auto --bgp-routing-mode=regional + ``` + ``` + gcloud compute firewall-rules create mtu9kfw --network mtu9k --allow tcp,icmp,udp --project=${PROJECT} + ``` + + When you create your TPUs, you need to indicate they should be part of this network. + + Here is an example of a queued-resources request on GCE using the `--network` flag (`--network=mtu9k`). + ``` + gcloud alpha compute tpus queued-resources create ${QR_ID} --node-prefix=${TPU_NAME} --node-count=${NUM_SLICES} --accelerator_type=${ACCELERATOR_TYPE} --runtime_version=${RUNTIME_VERSION} --network=mtu9k --project=${PROJECT} --zone=${ZONE} + ``` + Note: If you want to use only one slice, you need to replace node-prefix with node-id, and remove node-count. + + Here is an example of creating a GKE cluster with XPK using the `--network` and `--subnetwork` flags (`--network=mtu9k --subnetwork=mtu9k`). + ``` + export CLUSTER_ARGUMENTS="--network=mtu9k --subnetwork=mtu9k" + + python3 xpk/xpk.py cluster create --cluster ${YOUR_CLUSTER_NAME} --tpu-type ${ACCELERATOR_TYPE} --num-slices ${NUM_SLICES} --custom-cluster-arguments="${CLUSTER_ARGUMENTS}" + ``` + +### Run model config scripts on TPUs +1. You can run these model configs on the GCE platform using `multihost_runner.py` or `multihost_job.py`, or on the GKE platform using [XPK](https://github.com/google/xpk). Take a look at the [getting_started](https://github.com/google/maxtext/tree/main/getting_started) directory for directions on how to set up your TPUs and use these tools. + +2. Here are some example commands to run the model configs: + + Running with `multihost_runner.py` on GCE: + ``` + python3 multihost_runner.py --TPU_PREFIX=${TPU_PREFIX} --COMMAND="bash setup.sh && bash MaxText/configs/v5p/128b.sh RUN_NAME=${YOUR_RUN_NAME} OUTPUT_PATH=${MAXTEXT_OUTPUT_PATH} DATASET_PATH=${MAXTEXT_DATASET_PATH} PLATFORM=gce" + ``` + + Running with `multihost_job.py` on GCE: + ``` + python3 multihost_job.py --NUM_SLICES=${NUM_SLICES} --TPU_TYPE=${ACCELERATOR_TYPE} --VERSION=${RUNTIME_VERSION} --RUN_NAME=${RUN_NAME} --BUCKET_NAME=${GCS_BUCKET_NAME} --COMMAND="bash setup.sh && bash MaxText/configs/v5p/128b.sh RUN_NAME=${YOUR_RUN_NAME} OUTPUT_PATH=${MAXTEXT_OUTPUT_PATH} DATASET_PATH=${MAXTEXT_DATASET_PATH} PLATFORM=gce" + + # Add --CQR_EXTRA_ARGS="--network=mtu9k" to the command if you would like to use the custom MTU network. + ``` + + Running with `XPK` on GKE: + ``` + xpk workload create --cluster ${YOUR_CLUSTER_NAME} --docker-image gcr.io/${PROJECT}/${YOUR_IMAGE_NAME} --workload ${YOUR_RUN_NAME} --tpu-type=${ACCELERATOR_TYPE} --num-slices=${NUM_SLICES} --command "bash MaxText/configs/v5p/128b.sh OUTPUT_PATH=${MAXTEXT_OUTPUT_PATH} DATASET_PATH=${MAXTEXT_DATASET_PATH} PLATFORM=gke" + ``` + + Note: When running these scripts, be sure to specify the `PLATFORM` flag with the correct platform you are running on `"gce"` or `"gke"`. diff --git a/maxtext-setup/maxtext/MaxText/configs/base.yml b/maxtext-setup/maxtext/MaxText/configs/base.yml new file mode 100644 index 0000000000000000000000000000000000000000..170d71b62986350ecd82e05b0e441f85bd7aa542 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/base.yml @@ -0,0 +1,249 @@ +# Copyright 2023 Google LLC +# +# 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. + +# This sentinel is a reminder to choose a real run name. +# If there is already a checkpoint under this run, that checkpoint will auto-resume. +run_name: "" + +model_name: "default" # override config settings to match a specific model. other than the override, nothing should use this! +normalization_layer_epsilon: 1.e-05 + +################################## CHECKPOINTING ################################## +# Checkpointing makes the following choices in the following order, starting with (1): +# (1) If there is already a checkpoint for this run_name, we load the latest entire checkpoint. +# This ensures if we're resuming a run after preemption or hardware failure we lose minimum state. +# (2) Same priority and mutually exclusive -- you can't set both! +# * If load_parameters_path is set, we load a parameter only checkpoint from that path. +# * If load_full_state_path is set, we load a full state checkpoint from that path. +# (3) We don't load a checkpoint and initialize state instead! + +# Loads a just parameters from a specific directory +# e.g. gs://my-base-output-directory/my-previous-run-name/checkpoints/items/NUMBER or NUMBER/items +load_parameters_path: "" +# Loads a full checkpoint including optimizer state and step count from a specific directory +# e.g. gs://my-base-output-directory/my-previous-run-name/checkpoints/items/NUMBER or NUMBER/items +load_full_state_path: "" + +# If enable_checkpointing is true, an asynchronous checkpointer will be used if +# async_checkpointing is true, else a synchronous one is used. If you have +# problems with the checkpointer we recommend trying the synchronous one. +enable_checkpointing: True +async_checkpointing: True +checkpoint_period: 10_000 +# enables one replica to read the ckpt then broadcast to the rest +enable_single_replica_ckpt_restoring: False + +force_unroll: False # during generate_param_only_checkpoint should we unroll the loop? +############################### END CHECKPOINTING ################################## + + +reuse_example_batch: 0 # for testing TPU performance, this options repeated uses the same batch. + +metrics_file: "" # for testing, local file that stores scalar metrics. If empty, no metrics are written. +# If true save metrics such as loss and TFLOPS to GCS in {base_output_directory}/{run_name}/metrics/ +gcs_metrics: False + +# If true save config to GCS in {base_output_directory}/{run_name}/ +save_config_to_gcs: False + +# Activation dtypes. +dtype: "bfloat16" +quantization: "" #defaults to no quantization, i.e. bf16. possible alternative setting is 'int8' +quantize_kvcache: False + +# Shard the range finding operation for quantization. By default this is set to number of slices. +quantization_local_shard_count: -1 + +decoder_block: "llama2" # which style of DecoderBlock to use. +# Global parameter scale needs to be a power of 2. If you want finer grained control of the model sizes +# then you should explicitly set base_embed_dim, base_num_query_heads, base_num_kv_heads, +# base_mlp_dim, base_num_decoder_layers and/or head_dim. +weight_dtype: float32 +global_parameter_scale: 1 +base_emb_dim: 2048 +base_num_query_heads: 16 +base_num_kv_heads: 16 +base_mlp_dim: 7168 +base_num_decoder_layers: 16 +head_dim: 128 +# mixture of experts (moe) +num_experts: 1 +num_experts_per_tok: 1 +mlp_activations: ["silu", "linear"] +dropout_rate: 0 +logits_via_embedding: False +normalize_embedding_logits: True # whether to normlize pre-softmax logits if logits_via_embedding is true +logits_dot_in_fp32: True # whether to use fp32 in logits_dense or shared_embedding dot product for stability + +# Choose 'remat_policy' between 'minimal', 'save_dot_except_mlpwi', 'save_dot_except_mlp', 'save_qkv_proj', 'minimal_offloaded' and 'full'. +# These options offer a trade-off between speed (fastest to slowest) and HBM usage (highest to lowest) +remat_policy: 'full' +scan_layers: True +param_scan_axis: 1 +attention: 'autoselected' # Supported attention: autoselected, dot_product, flash, cudnn_flash_te + +# Combine matmuls for QKV and MLP +fused_qkv: False +fused_mlp: False + +record_internal_nn_metrics: 0 + +# Output directory +# Create a GCS bucket, e.g. my-maxtext-outputs and set this to "gs://my-maxtext-outputs/" +base_output_directory: "" + +# Jax cache directory +jax_cache_dir: "~/jax_cache" + +# Hardware +hardware: 'tpu' # Supported hardware types are 'tpu', 'gpu', 'gpu_multiprocess' and 'cpu' + +# Parallelism +mesh_axes: ['data', 'fsdp', 'fsdp_transpose', 'sequence', 'tensor', 'autoregressive'] +logical_axis_rules: [ + ['activation_batch', ['data', 'fsdp', 'fsdp_transpose',]], + ['activation_heads', ['tensor','sequence']], + ['activation_length', 'sequence'], + ['activation_embed', 'tensor'], + ['activation_mlp', 'tensor'], + ['activation_kv', 'tensor'], + ['activation_vocab', ['tensor', 'sequence']], + ['activation_vocab', 'tensor'], + ['activation_vocab', 'sequence'], + ['mlp', ['fsdp_transpose', 'tensor', 'autoregressive']], + ['vocab', ['tensor', 'autoregressive']], + ['embed', ['fsdp', 'fsdp_transpose', 'sequence']], + ['embed', ['fsdp', 'sequence']], + ['heads', ['tensor', 'autoregressive']], + ['kv', []], + ['cache_batch', []], + ['cache_heads', ['autoregressive', 'tensor']], + ['cache_kv', []], + ['cache_sequence', []], + ] +data_sharding: [['data', 'fsdp', 'fsdp_transpose', 'sequence', 'tensor', 'autoregressive']] + +# One axis for each parallelism type may hold a placeholder (-1) +# value to auto-shard based on available slices and devices. +# By default, product of the DCN axes should equal number of slices +# and product of the ICI axes should equal number of devices per slice. +dcn_data_parallelism: -1 # recommended DCN axis to be auto-sharded +dcn_fsdp_parallelism: 1 +dcn_fsdp_transpose_parallelism: 1 +dcn_sequence_parallelism: 1 # never recommended +dcn_tensor_parallelism: 1 # never recommeneded +dcn_autoregressive_parallelism: 1 # never recommended +ici_data_parallelism: 1 +ici_fsdp_parallelism: -1 # recommended ICI axis to be auto-sharded +ici_fsdp_transpose_parallelism: 1 +ici_sequence_parallelism: 1 +ici_tensor_parallelism: 1 +ici_autoregressive_parallelism: 1 + +# The number of TPU slices is automatically determined, you should not set this explicitly. For ahead of time compilation, +# you should set compile_toplogy_num_slices, which will in turn set this value. For non-TPU environments this is set to 1. +num_slices: -1 + +# Dataset +# Replace with your path given as argument in download_dataset.sh, e.g. "gs://my-maxtext-dataset/" +dataset_path: "" +vocab_size: 32_000 # powers of 2 for sharding +tokenizer_path: "assets/tokenizer.llama2" +dataset_name: 'c4/en:3.0.1' +eval_dataset_name: 'c4/en:3.0.1' +eval_split: 'validation' +per_device_batch_size: 12.0 +eval_per_device_batch_size: 0 +max_corpus_chars: 10_000_000 +dataset_type: c4 # must be c4 or synthetic + +# Setting for grain +grain_worker_count: 4 + +# Training loop +steps: 150_001 # If set to -1 then will inherit value from learning_rate_schedule_steps +log_period: 100 # Flushes Tensorboard + +# We take inspiration from Llama2's learning rate (LR) schedule, see https://arxiv.org/pdf/2307.09288.pdf section 2.2 +# Learning rate schedule has either two or three parts: +# 1) Linear warmup from 0 to [learning_rate] over steps 0 to [learning_rate_schedule_steps * warmup_steps_fraction] +# 2) Cosine decay from [learning_rate] to [learning_rate * cosine_learning_rate_final_fraction] from warmup to learning_rate_schedule_steps +# 3) Constant learning rate of 0 from learning_rate_schedule_steps to steps. +# The zero learning rate section can be used to more accurately measure the fully trained model's performance. +learning_rate: 3.e-5 +cosine_learning_rate_final_fraction: 0.1 +warmup_steps_fraction: 0.1 +learning_rate_schedule_steps: -1 # By default the length of the schedule is set to the number of steps. +# However you may choose a longer schedule (learning_rate_schedule_steps > steps), in which case the training will end before +# dropping fully down. Or you may choose a shorter schedule, where the unspecified steps will have a learning rate of 0. + +max_target_length: 2048 # Maximum sequence length +max_prefill_predict_length: 64 # Maximum length for the prefill when doing autoregression +prompt: "I love to" # Prompt for language model sampling. +load_from_prefill_dir: False # If true, decode.py doesn't "prefill" but just reads from directory +prefill_cache_dir: "" # If set and load_from_prefill_dir, decode.py reads from directory. If set, decode.py writes to directory +autoregressive_decode_assert: "" + +enable_profiler: False +# If set to true, upload all profiler xplane results from all hosts. Otherwise, only upload the xplane reuslt from the first host. +upload_all_profiler_results: False +# Skip first n steps for profiling, to omit things like compilation and to give +# the iteration time a chance to stabilize. +skip_first_n_steps_for_profiler: 1 +# Profile for a small number of steps to avoid a large profile file size. +profiler_steps: 5 + +# When dropout is false the model is a deterministic function of the +# data_shuffle_seed and init_weights_seed (i.e. reproducible losses) +enable_dropout: True +enable_data_shuffling: True +data_shuffle_seed: 0 +init_weights_seed: 0 + +# You may disable clipping by setting gradient_clipping_threshold to zero. +gradient_clipping_threshold: 1.0 + +# AdamW optimizer parameters +# We use AdamW following Llama2's training details, see https://arxiv.org/pdf/2307.09288.pdf section 2.2 +opt_type: "adamw" # one of "adam_pax" or "adamw" +adam_b1: 0.9 # Exponential decay rate to track the first moment of past gradients. +adam_b2: 0.95 # Exponential decay rate to track the second moment of past gradients. +adam_eps: 1.e-8 # A small constant applied to denominator outside of the square root. +adam_eps_root: 0. # A small constant applied to denominator inside the square root. +adam_weight_decay: 0.1 # AdamW Weight decay + +# Stack trace parameters +collect_stack_trace: False +stack_trace_to_cloud: False # Uploads to cloud logging if True, else to the console if False. +stack_trace_interval_seconds: 600 # Stack trace collection frequency in seconds. + +# Use iota operator in Embed +use_iota_embed: False +# use positional embedding +use_untrainable_positional_embedding: False +trainable_position_size: -1 # enable gpt3 position embedding with a positive trainable_position_size + +# Ahead of time Compilation (aka AOT) +# Only set these arguments if you are running train_compile or loading a compiled train step. +compiled_trainstep_file: "" # Name of saved serialized compiled train_step, e.g. compiled_train_v5e-256.pickle +compile_topology: '' # Target hardware version, e.g. 'v5e-256' +compile_topology_num_slices: -1 # Number of target slices, set to a positive integer. + +decode_sampling_strategy: "greedy" # decode_sampling_strategy should be one of greedy, weighted, nucleus, or topk +decode_sampling_nucleus_p: -1 # set if you're doing nucleus / top-p +decode_sampling_top_k: 0 # set if you're doing top-k +decode_sampling_temperature: 1. + +eval_interval: -1 # the specific number of train step between eval_step +target_eval_loss: 0. # early stop once reaching target eval_loss diff --git a/maxtext-setup/maxtext/MaxText/configs/experimental/1024b.sh b/maxtext-setup/maxtext/MaxText/configs/experimental/1024b.sh new file mode 100644 index 0000000000000000000000000000000000000000..4ac165d16887fa167b7b768983571af5fc0a01ab --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/experimental/1024b.sh @@ -0,0 +1,28 @@ +echo "Running 1024b.sh" +# Example command to invoke this script +# bash MaxText/configs/experimental/1024b.sh + +# Stop execution if any command exits with error +set -e + +export OUTPUT_PATH="gs://maxtext-experiments-multipod" +export DATASET_PATH="gs://maxtext-dataset/" + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Use preflight.sh to set up env based on platform +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=20 per_device_batch_size=2 enable_checkpointing=false\ + enable_profiler=false remat_policy=full global_parameter_scale=1024\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=16\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization="" diff --git a/maxtext-setup/maxtext/MaxText/configs/experimental/128b.sh b/maxtext-setup/maxtext/MaxText/configs/experimental/128b.sh new file mode 100644 index 0000000000000000000000000000000000000000..8c7c818302b7fec604c5008e88085e835c0d34b8 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/experimental/128b.sh @@ -0,0 +1,28 @@ +echo "Running 128b.sh" +# Example command to invoke this script +# bash MaxText/configs/experimental/128b.sh + +# Stop execution if any command exits with error +set -e + +export OUTPUT_PATH="gs://maxtext-experiments-multipod" +export DATASET_PATH="gs://maxtext-dataset/" + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Use preflight.sh to set up env based on platform +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=2 enable_checkpointing=false\ + enable_profiler=false remat_policy=minimal global_parameter_scale=128\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=8\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization=""\ diff --git a/maxtext-setup/maxtext/MaxText/configs/experimental/256b.sh b/maxtext-setup/maxtext/MaxText/configs/experimental/256b.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e6a5552f2b40dac6f1d581e258debe3c138a7d0 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/experimental/256b.sh @@ -0,0 +1,28 @@ +echo "Running 256b.sh" +# Example command to invoke this script +# bash MaxText/configs/experimental/256b.sh + +# Stop execution if any command exits with error +set -e + +export OUTPUT_PATH="gs://maxtext-experiments-multipod" +export DATASET_PATH="gs://maxtext-dataset/" + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Use preflight.sh to set up env based on platform +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=20 per_device_batch_size=2 enable_checkpointing=false\ + enable_profiler=false remat_policy=minimal global_parameter_scale=256\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=8\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization="" diff --git a/maxtext-setup/maxtext/MaxText/configs/experimental/32b.sh b/maxtext-setup/maxtext/MaxText/configs/experimental/32b.sh new file mode 100644 index 0000000000000000000000000000000000000000..dd43fc6c16a0aae919c6e69ca67ce47ed78034cc --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/experimental/32b.sh @@ -0,0 +1,28 @@ +echo "Running 32b.sh" +# Example command to invoke this script +# bash MaxText/configs/experimental/32b.sh + +# Stop execution if any command exits with error +set -e + +export OUTPUT_PATH="gs://maxtext-experiments-multipod" +export DATASET_PATH="gs://maxtext-dataset/" + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Use preflight.sh to set up env based on platform +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=8 enable_checkpointing=false\ + enable_profiler=false remat_policy=minimal global_parameter_scale=32\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=4\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization=""\ diff --git a/maxtext-setup/maxtext/MaxText/configs/experimental/512b.sh b/maxtext-setup/maxtext/MaxText/configs/experimental/512b.sh new file mode 100644 index 0000000000000000000000000000000000000000..55d119877a526337a40ee919483906d6050e3fe2 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/experimental/512b.sh @@ -0,0 +1,28 @@ +echo "Running 512b.sh" +# Example command to invoke this script +# bash MaxText/configs/experimental/512b.sh + +# Stop execution if any command exits with error +set -e + +export OUTPUT_PATH="gs://maxtext-experiments-multipod" +export DATASET_PATH="gs://maxtext-dataset/" + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Use preflight.sh to set up env based on platform +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=20 per_device_batch_size=2 enable_checkpointing=false\ + enable_profiler=false remat_policy=full global_parameter_scale=512\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=16\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization="" diff --git a/maxtext-setup/maxtext/MaxText/configs/experimental/64b.sh b/maxtext-setup/maxtext/MaxText/configs/experimental/64b.sh new file mode 100644 index 0000000000000000000000000000000000000000..e375697b399bc00d3d5473df0c25e19ef4975413 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/experimental/64b.sh @@ -0,0 +1,28 @@ +echo "Running 64b.sh" +# Example command to invoke this script +# bash MaxText/configs/experimental/64b.sh + +# Stop execution if any command exits with error +set -e + +export OUTPUT_PATH="gs://maxtext-experiments-multipod" +export DATASET_PATH="gs://maxtext-dataset/" + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Use preflight.sh to set up env based on platform +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=4 enable_checkpointing=false\ + enable_profiler=false remat_policy=minimal global_parameter_scale=64\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=4\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization=""\ diff --git a/maxtext-setup/maxtext/MaxText/configs/gpu_smoke_test.yml b/maxtext-setup/maxtext/MaxText/configs/gpu_smoke_test.yml new file mode 100644 index 0000000000000000000000000000000000000000..cafee5387df1235c1182d0622929066c5bfa1ed9 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/gpu_smoke_test.yml @@ -0,0 +1,15 @@ +base_config: "base.yml" + +hardware: "gpu" +attention: "dot_product" +base_emb_dim: 8 +base_emb_dim: 8 +base_num_query_heads: 4 +base_num_kv_heads: 4 +base_mlp_dim: 32 +base_num_decoder_layers: 8 +head_dim: 16 +per_device_batch_size: 2 +max_target_length: 1024 +dataset_type: "synthetic" +steps: 10 diff --git a/maxtext-setup/maxtext/MaxText/configs/llama2_7b_single_host_gpu.yml b/maxtext-setup/maxtext/MaxText/configs/llama2_7b_single_host_gpu.yml new file mode 100644 index 0000000000000000000000000000000000000000..e60701360c9d978aeca963f0c9b661a8a019a8dd --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/llama2_7b_single_host_gpu.yml @@ -0,0 +1,17 @@ +base_config: "base.yml" + +hardware: "gpu" +attention: "cudnn_flash_te" + +learning_rate_schedule_steps: 150001 + +model_name: llama2-7b + +max_target_length: 1024 +dataset_type: "synthetic" +steps: 10 + +vocab_relative_path: tokenizer.llama2 +rms_norm_epsilon: 1e-05 + +prompt: "I love to" diff --git a/maxtext-setup/maxtext/MaxText/configs/models/gemma-2b.yml b/maxtext-setup/maxtext/MaxText/configs/models/gemma-2b.yml new file mode 100644 index 0000000000000000000000000000000000000000..985b240dc3ec14daadfd6c20bba43ef1a159ebdb --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/gemma-2b.yml @@ -0,0 +1,27 @@ +# Copyright 2023 Google LLC +# +# 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. + +# model config for gemma-2b + +base_emb_dim: 2048 +base_num_query_heads: 8 +base_num_kv_heads: 1 +base_mlp_dim: 16384 +base_num_decoder_layers: 18 +head_dim: 256 +mlp_activations: ["gelu","linear"] +vocab_size: 256128 +decoder_block: "gemma" +normalization_layer_epsilon: 1.e-06 +logits_via_embedding: True \ No newline at end of file diff --git a/maxtext-setup/maxtext/MaxText/configs/models/gemma-7b.yml b/maxtext-setup/maxtext/MaxText/configs/models/gemma-7b.yml new file mode 100644 index 0000000000000000000000000000000000000000..3201b37a5cded8e9b35b3b6641f90e23237e5c9c --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/gemma-7b.yml @@ -0,0 +1,27 @@ +# Copyright 2023 Google LLC +# +# 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. + +# model config for gemma-7b + +base_emb_dim: 3072 +base_num_query_heads: 16 +base_num_kv_heads: 16 +base_mlp_dim: 24576 +base_num_decoder_layers: 28 +head_dim: 256 +mlp_activations: ["gelu","linear"] +vocab_size: 256128 +decoder_block: "gemma" +normalization_layer_epsilon: 1.e-06 +logits_via_embedding: True \ No newline at end of file diff --git a/maxtext-setup/maxtext/MaxText/configs/models/gpt3-175b.yml b/maxtext-setup/maxtext/MaxText/configs/models/gpt3-175b.yml new file mode 100644 index 0000000000000000000000000000000000000000..fa1db0f68051db0dec565b0b4c2960262787b70b --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/gpt3-175b.yml @@ -0,0 +1,44 @@ +# Copyright 2023 Google LLC +# +# 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. + +# model config for gpt3-175b + +base_emb_dim: 12288 +base_num_query_heads: 96 +base_num_kv_heads: 96 +base_mlp_dim: 49152 +base_num_decoder_layers: 96 +head_dim: 128 +trainable_position_size: 16384 +mlp_activations: ["gelu"] +vocab_size: 50304 +enable_dropout: False +logits_via_embedding: True +normalize_embedding_logits: False +logits_dot_in_fp32: False +normalization_layer_epsilon: 1.e-05 +use_iota_embed: True +fused_qkv: True +opt_type: "adam_pax" +decoder_block: "gpt3" +dataset_path: "gs://mlperf-llm-public2" +dataset_name: "c4/en:3.0.4" +eval_dataset_name: "c4/en:3.0.5" +gradient_clipping_threshold: 1. +adam_b1: 0.9 +adam_b2: 0.95 +adam_eps: 1.e-8 +adam_weight_decay: 0.1 +checkpoint_period: 10_000 +target_eval_loss: 2.69 diff --git a/maxtext-setup/maxtext/MaxText/configs/models/gpt3-22b.yml b/maxtext-setup/maxtext/MaxText/configs/models/gpt3-22b.yml new file mode 100644 index 0000000000000000000000000000000000000000..eb6d58d73840fedeb6fe6943699f994cc63cc2c8 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/gpt3-22b.yml @@ -0,0 +1,40 @@ +# Copyright 2023 Google LLC +# +# 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. + +# model config for gpt3-22b + +base_emb_dim: 6144 +base_num_query_heads: 24 +base_num_kv_heads: 24 +base_mlp_dim: 24576 +base_num_decoder_layers: 48 +head_dim: 256 +max_target_length: 1024 +trainable_position_size: 16384 +mlp_activations: ["gelu"] +vocab_size: 32768 +enable_dropout: False +logits_via_embedding: True +normalize_embedding_logits: False +logits_dot_in_fp32: False +normalization_layer_epsilon: 1.e-05 +use_iota_embed: True +fused_qkv: True +opt_type: "adam_pax" +decoder_block: "gpt3" +gradient_clipping_threshold: 1. +adam_b1: 0.9 +adam_b2: 0.95 +adam_eps: 1.e-8 +adam_weight_decay: 0.1 diff --git a/maxtext-setup/maxtext/MaxText/configs/models/gpt3-52k.yml b/maxtext-setup/maxtext/MaxText/configs/models/gpt3-52k.yml new file mode 100644 index 0000000000000000000000000000000000000000..7f32371cca1373b2cbc9a663e2a9d418d7a648f6 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/gpt3-52k.yml @@ -0,0 +1,40 @@ +# Copyright 2023 Google LLC +# +# 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. + +# model config for gpt3-52k, i.e. a fake and small model for testing purpose only + +base_emb_dim: 16 +base_num_query_heads: 2 +base_num_kv_heads: 2 +base_mlp_dim: 64 +base_num_decoder_layers: 1 +head_dim: 8 +trainable_position_size: 2048 +mlp_activations: ["gelu"] +vocab_size: 1024 +enable_dropout: False +logits_via_embedding: True +normalize_embedding_logits: False +logits_dot_in_fp32: False +normalization_layer_epsilon: 1.e-05 +use_iota_embed: True +fused_qkv: True +opt_type: "adam_pax" +decoder_block: "gpt3" +gradient_clipping_threshold: 1. +adam_b1: 0.9 +adam_b2: 0.95 +adam_eps: 1.e-8 +adam_weight_decay: 0.1 +attention: "dot_product" # head_dim 8 is too small for splash/flash attention diff --git a/maxtext-setup/maxtext/MaxText/configs/models/gpt3-6b.yml b/maxtext-setup/maxtext/MaxText/configs/models/gpt3-6b.yml new file mode 100644 index 0000000000000000000000000000000000000000..14d82c970c33d6049e9f9acf210d71c72b78d13b --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/gpt3-6b.yml @@ -0,0 +1,40 @@ +# Copyright 2023 Google LLC +# +# 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. + +# model config for gpt3-6b + +base_emb_dim: 3072 +base_num_query_heads: 12 +base_num_kv_heads: 12 +base_mlp_dim: 12288 +base_num_decoder_layers: 48 +head_dim: 256 +max_target_length: 1024 +trainable_position_size: 16384 +mlp_activations: ["gelu"] +vocab_size: 32768 +enable_dropout: False +logits_via_embedding: True +normalize_embedding_logits: False +logits_dot_in_fp32: False +normalization_layer_epsilon: 1.e-05 +use_iota_embed: True +fused_qkv: True +opt_type: "adam_pax" +decoder_block: "gpt3" +gradient_clipping_threshold: 1. +adam_b1: 0.9 +adam_b2: 0.95 +adam_eps: 1.e-8 +adam_weight_decay: 0.1 diff --git a/maxtext-setup/maxtext/MaxText/configs/models/llama2-13b.yml b/maxtext-setup/maxtext/MaxText/configs/models/llama2-13b.yml new file mode 100644 index 0000000000000000000000000000000000000000..b0bbb6262939e886d89bd077ccc577968127fd05 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/llama2-13b.yml @@ -0,0 +1,28 @@ +# Copyright 2024 Google LLC +# +# 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. + +# model config for llama2-13b + +base_emb_dim: 5120 +base_num_query_heads: 40 +base_num_kv_heads: 40 +base_mlp_dim: 13824 +base_num_decoder_layers: 40 +head_dim: 128 +mlp_activations: ["silu","linear"] +vocab_size: 32000 +enable_dropout: False +logits_via_embedding: False +normalization_layer_epsilon: 1.0e-5 +decoder_block: "llama2" \ No newline at end of file diff --git a/maxtext-setup/maxtext/MaxText/configs/models/llama2-70b.yml b/maxtext-setup/maxtext/MaxText/configs/models/llama2-70b.yml new file mode 100644 index 0000000000000000000000000000000000000000..d277c7d8849134cff39b61bb776553edeee9fa83 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/llama2-70b.yml @@ -0,0 +1,27 @@ +# Copyright 2023 Google LLC +# +# 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. + +# model config for llama2-7b + +base_emb_dim: 8192 +base_num_query_heads: 64 +base_num_kv_heads: 8 +base_mlp_dim: 28672 +base_num_decoder_layers: 80 +head_dim: 128 +mlp_activations: ["silu","linear"] +vocab_size: 32000 +logits_via_embedding: False +normalization_layer_epsilon: 1.0e-5 +decoder_block: "llama2" diff --git a/maxtext-setup/maxtext/MaxText/configs/models/llama2-7b.yml b/maxtext-setup/maxtext/MaxText/configs/models/llama2-7b.yml new file mode 100644 index 0000000000000000000000000000000000000000..fa1460df38d05db94f57476f8f31096c802cbb54 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/llama2-7b.yml @@ -0,0 +1,28 @@ +# Copyright 2023 Google LLC +# +# 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. + +# model config for llama2-7b + +base_emb_dim: 4096 +base_num_query_heads: 32 +base_num_kv_heads: 32 +base_mlp_dim: 11008 +base_num_decoder_layers: 32 +head_dim: 128 +mlp_activations: ["silu","linear"] +vocab_size: 32000 +enable_dropout: False +logits_via_embedding: False +normalization_layer_epsilon: 1.0e-5 +decoder_block: "llama2" diff --git a/maxtext-setup/maxtext/MaxText/configs/models/mistral-7b.yml b/maxtext-setup/maxtext/MaxText/configs/models/mistral-7b.yml new file mode 100644 index 0000000000000000000000000000000000000000..39e234e14726410c43933c0b6962b463f3c5d1af --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/mistral-7b.yml @@ -0,0 +1,28 @@ +# Copyright 2023 Google LLC +# +# 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. + +# model config for mistral-7b + +base_emb_dim: 4096 +base_num_query_heads: 32 +base_num_kv_heads: 8 +base_mlp_dim: 14336 +base_num_decoder_layers: 32 +head_dim: 128 +mlp_activations: ["silu","linear"] +vocab_size: 32000 +enable_dropout: False +logits_via_embedding: False +normalization_layer_epsilon: 1.0e-5 +decoder_block: "mistral" diff --git a/maxtext-setup/maxtext/MaxText/configs/models/mixtral-8x7b.yml b/maxtext-setup/maxtext/MaxText/configs/models/mixtral-8x7b.yml new file mode 100644 index 0000000000000000000000000000000000000000..c367b94a8653219274c13fb550fa97f163772df6 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/models/mixtral-8x7b.yml @@ -0,0 +1,30 @@ +# Copyright 2024 Google LLC +# +# 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. + +# model config for mixtral-8x7b + +base_emb_dim: 4096 +base_num_query_heads: 32 +base_num_kv_heads: 8 +base_mlp_dim: 14336 +base_num_decoder_layers: 32 +head_dim: 128 +mlp_activations: ["silu","linear"] +vocab_size: 32000 +enable_dropout: False +logits_via_embedding: False +normalization_layer_epsilon: 1.0e-5 +num_experts: 8 +num_experts_per_tok: 2 +decoder_block: "mistral" diff --git a/maxtext-setup/maxtext/MaxText/configs/tpu_smoke_test.yml b/maxtext-setup/maxtext/MaxText/configs/tpu_smoke_test.yml new file mode 100644 index 0000000000000000000000000000000000000000..bdac0ff34929113532b5c72d591110a4a037dd3d --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/tpu_smoke_test.yml @@ -0,0 +1,14 @@ +base_config: "base.yml" + +hardware: "tpu" +async_checkpointing: false +attention: autoselected +base_emb_dim: 32 +base_num_query_heads: 8 +base_num_kv_heads: 8 +base_mlp_dim: 32 +base_num_decoder_layers: 8 +dataset_type: "synthetic" +head_dim: 128 +per_device_batch_size: 1 +steps: 10 diff --git a/maxtext-setup/maxtext/MaxText/configs/v4/22b.sh b/maxtext-setup/maxtext/MaxText/configs/v4/22b.sh new file mode 100644 index 0000000000000000000000000000000000000000..df19c7cd10f6aa2daf6df3a6effe89cce096892f --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v4/22b.sh @@ -0,0 +1,52 @@ +# Copyright 2023 Google LLC +# +# 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. + +echo "Running 22b.sh" +# 22B parameter model. +# This config will work out of the box for any number of v4-128 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script for training: +# bash MaxText/configs/v4/22b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v4/22b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v4-128 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_enable_async_all_gather=true TPU_MEGACORE=MEGACORE_DENSE" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + ici_fsdp_parallelism=64 steps=10 per_device_batch_size=13 enable_profiler=true remat_policy=full\ + base_emb_dim=6144 base_num_kv_heads=24 base_num_query_heads=24 base_mlp_dim=24576 base_num_decoder_layers=48\ + base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH diff --git a/maxtext-setup/maxtext/MaxText/configs/v4/52b.sh b/maxtext-setup/maxtext/MaxText/configs/v4/52b.sh new file mode 100644 index 0000000000000000000000000000000000000000..89d1adf92cdde2da0fb59480e0eaf2c4fdb38333 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v4/52b.sh @@ -0,0 +1,53 @@ +# Copyright 2023 Google LLC +# +# 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. + +echo "Running 52b.sh" +# 52B parameter model. +# This config will work out of the box for any number of v4-384 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v4/52b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v4/52b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v4-384 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_enable_async_all_gather=true TPU_MEGACORE=MEGACORE_DENSE" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + enable_profiler=true enable_checkpointing=false steps=10\ + ici_fsdp_parallelism=192 ici_tensor_parallelism=1 per_device_batch_size=7 remat_policy=full\ + base_num_decoder_layers=32 base_emb_dim=12288 base_mlp_dim=49152 base_num_query_heads=32 base_num_kv_heads=32 learning_rate=1e-8\ + base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH diff --git a/maxtext-setup/maxtext/MaxText/configs/v4/README.md b/maxtext-setup/maxtext/MaxText/configs/v4/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9675d24412d3702cd6fd890b8b58ef1a76266849 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v4/README.md @@ -0,0 +1,33 @@ + + +# High Performance Model Configs on TPU v4 +Expected performance results for 22B and 52B parameter models running on TPU v4: + + +### 22B model +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | ---------------- | ----- | +| 1x v4-128 | 156 | 56.7% | +| 2x v4-128 | 152 | 55.2% | +| 4x v4-128 | 149 | 54.3% | +| 8x v4-128 | 146 | 53.2% | + +### 52B model +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | ---------------- | ----- | +| 1x v4-384 | 154 | 56.0% | +| 2x v4-384 | 162 | 58.9% | # this is quirkily higher than single slice because of choices made by the compiler, not for a fundamental reason. \ No newline at end of file diff --git a/maxtext-setup/maxtext/MaxText/configs/v5e/128b.sh b/maxtext-setup/maxtext/MaxText/configs/v5e/128b.sh new file mode 100644 index 0000000000000000000000000000000000000000..7e3910410b9b56eb5a387944054fcafb0571098e --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5e/128b.sh @@ -0,0 +1,44 @@ +echo "Running 128b.sh" +# 128B parameter model. +# This config will work out of the box for any number of v5e-256 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5e/128b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5e/128b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5e-256 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" # Can be "gke" or "gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" + +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=1 enable_checkpointing=false\ + enable_profiler=false remat_policy=minimal_offloaded global_parameter_scale=128\ + ici_fsdp_parallelism=16 ici_tensor_parallelism=16\ + max_target_length=2048 base_output_directory=gs://runner-maxtext-logs\ + use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic attention='flash' gcs_metrics=true\ + fused_qkv=True fused_mlp=True\ + diff --git a/maxtext-setup/maxtext/MaxText/configs/v5e/16b.sh b/maxtext-setup/maxtext/MaxText/configs/v5e/16b.sh new file mode 100644 index 0000000000000000000000000000000000000000..31e3f7673a522680a6ceaaa2b42c5c0859dfe56d --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5e/16b.sh @@ -0,0 +1,40 @@ +echo "Running 16b.sh" +# 16B parameter model. +# This config will work out of the box for any number of v5e-256 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5e/16b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5e/16b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5e-256 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=6 enable_checkpointing=false\ + enable_profiler=false remat_policy=full global_parameter_scale=16\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic attention='flash' gcs_metrics=true diff --git a/maxtext-setup/maxtext/MaxText/configs/v5e/32b.sh b/maxtext-setup/maxtext/MaxText/configs/v5e/32b.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee310f4af66bfd893924874a4af4cc6802b753df --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5e/32b.sh @@ -0,0 +1,40 @@ +echo "Running 32b.sh" +# 32B parameter model. +# This config will work out of the box for any number of v5e-256 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5e/32b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5e/32b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5e-256 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=4 enable_checkpointing=false\ + enable_profiler=false remat_policy=full global_parameter_scale=32\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic attention='flash' gcs_metrics=true diff --git a/maxtext-setup/maxtext/MaxText/configs/v5e/64b.sh b/maxtext-setup/maxtext/MaxText/configs/v5e/64b.sh new file mode 100644 index 0000000000000000000000000000000000000000..a75fa996183816add3d37aaa5b84f6a8c7a9b6bf --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5e/64b.sh @@ -0,0 +1,40 @@ +echo "Running 64b.sh" +# 64B parameter model. +# This config will work out of the box for any number of v5e-256 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5e/64b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5e/64b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5e-256 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=2 enable_checkpointing=false\ + enable_profiler=false remat_policy=full global_parameter_scale=64\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic attention='flash' gcs_metrics=true diff --git a/maxtext-setup/maxtext/MaxText/configs/v5e/README.md b/maxtext-setup/maxtext/MaxText/configs/v5e/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e4a0582a6342df191a90cf3ff494e8073037a0a7 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5e/README.md @@ -0,0 +1,28 @@ + + +# High Performance Model Configs on TPU v5e +Expected performance results for 16B, 32B, 64B, and 128B parameter models running on TPU v5e: + + +| Hardware | 16B TFLOP/sec/chip | 16B MFU | 32B TFLOP/sec/chip | 32B MFU | 64B TFLOP/sec/chip | 64B MFU | 128B TFLOP/sec/chip | 128B MFU | +| ----------- | -----------------: | ------- | -----------------: | ------- | -----------------: | ------- | ------------------: | -------- | +| 1x v5e-256 | 120 | 61.10% | 132 | 66.86% | 118 | 59.90% | 110 | 56.06% | +| 2x v5e-256 | 117 | 59.37% | 128 | 64.81% | 112 | 56.66% | 110 | 55.82% | +| 4x v5e-256 | 117 | 59.14% | 126 | 64.10% | 110 | 55.85% | 108 | 54.93% | +| 8x v5e-256 | 115 | 58.27% | 125 | 63.67% | 108 | 54.96% | 104 | 52.93% | +| 16x v5e-256 | 111 | 56.56% | 123 | 62.26% | 105 | 53.29% | 100 | 50.86% | +| 32x v5e-256 | 108 | 54.65% | 119 | 60.40% | 99 | 50.18% | 91 | 46.25% | diff --git a/maxtext-setup/maxtext/MaxText/configs/v5p/1024b.sh b/maxtext-setup/maxtext/MaxText/configs/v5p/1024b.sh new file mode 100644 index 0000000000000000000000000000000000000000..b8c9258936d2c8ed04013ccdf885c166dc2fc7aa --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5p/1024b.sh @@ -0,0 +1,41 @@ +echo "Running 1024b.sh" +# 1024B parameter model. +# This config will work out of the box for any number of v5p-2048 or v5p-4096 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5p/1024b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5p/1024b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5p-2048 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=20 per_device_batch_size=2 enable_checkpointing=false\ + enable_profiler=false remat_policy=full global_parameter_scale=1024\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=16\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization="" diff --git a/maxtext-setup/maxtext/MaxText/configs/v5p/128b.sh b/maxtext-setup/maxtext/MaxText/configs/v5p/128b.sh new file mode 100644 index 0000000000000000000000000000000000000000..1e0616314808734215c5632da8b3136b8d986c5b --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5p/128b.sh @@ -0,0 +1,41 @@ +echo "Running 128b.sh" +# 128B parameter model. +# This config will work out of the box for any number of v5p-256 or v5p-512 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5p/128b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5p/128b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5p-256 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=1 enable_checkpointing=false\ + enable_profiler=false remat_policy=minimal global_parameter_scale=128\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=8\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization=""\ diff --git a/maxtext-setup/maxtext/MaxText/configs/v5p/256b.sh b/maxtext-setup/maxtext/MaxText/configs/v5p/256b.sh new file mode 100644 index 0000000000000000000000000000000000000000..5776706c65444073f9febf2ee17ad697edb50d06 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5p/256b.sh @@ -0,0 +1,41 @@ +echo "Running 256b.sh" +# 256B parameter model. +# This config will work out of the box for any number of v5p-1024 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5p/256b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5p/256b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5p-1024 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=20 per_device_batch_size=1 enable_checkpointing=false\ + enable_profiler=false remat_policy=minimal global_parameter_scale=256\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=8\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization="" diff --git a/maxtext-setup/maxtext/MaxText/configs/v5p/32b.sh b/maxtext-setup/maxtext/MaxText/configs/v5p/32b.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a7d9fa9592b1e94face19f8f23c88dc25361436 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5p/32b.sh @@ -0,0 +1,41 @@ +echo "Running 32b.sh" +# 32B parameter model. +# This config will work out of the box for any number of v5p-128 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5p/32b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5p/32b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5p-128 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=6 enable_checkpointing=false\ + enable_profiler=false remat_policy=minimal global_parameter_scale=32\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=4\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization=""\ diff --git a/maxtext-setup/maxtext/MaxText/configs/v5p/512b.sh b/maxtext-setup/maxtext/MaxText/configs/v5p/512b.sh new file mode 100644 index 0000000000000000000000000000000000000000..4bca08b2965da30bbdc028efea9c8fd55407a32d --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5p/512b.sh @@ -0,0 +1,41 @@ +echo "Running 512b.sh" +# 512B parameter model. +# This config will work out of the box for any number of v5p-1024 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5p/512b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5p/512b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5p-1024 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=20 per_device_batch_size=2 enable_checkpointing=false\ + enable_profiler=false remat_policy=full global_parameter_scale=512\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=8\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization="" diff --git a/maxtext-setup/maxtext/MaxText/configs/v5p/64b.sh b/maxtext-setup/maxtext/MaxText/configs/v5p/64b.sh new file mode 100644 index 0000000000000000000000000000000000000000..b4f422bc7f0fa318d086e66dbbab9f34297404bc --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5p/64b.sh @@ -0,0 +1,41 @@ +echo "Running 64b.sh" +# 64B parameter model. +# This config will work out of the box for any number of v5p-128 slices. +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# +# Example to invoke this script: +# bash MaxText/configs/v5p/64b.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" +# +# Example to AOT compile: +# bash MaxText/configs/v5p/64b.sh EXECUTABLE=train_compile.py M_COMPILE_TOPOLOGY=v5p-128 M_COMPILE_TOPOLOGY_NUM_SLICES=2 + + +# Stop execution if any command exits with error +set -e + +export PLATFORM="gce" +export EXECUTABLE="train.py" # or train_compile.py + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_megacore_fusion_allow_ags=false --xla_enable_async_collective_permute=true --xla_tpu_enable_ag_backward_pipelining=true --xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/$EXECUTABLE MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=30 per_device_batch_size=3 enable_checkpointing=false\ + enable_profiler=false remat_policy=minimal global_parameter_scale=64\ + ici_fsdp_parallelism=-1 ici_tensor_parallelism=4\ + max_target_length=2048 base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH use_iota_embed=true reuse_example_batch=1\ + dataset_type=synthetic gcs_metrics=true attention='flash' quantization=""\ diff --git a/maxtext-setup/maxtext/MaxText/configs/v5p/README.md b/maxtext-setup/maxtext/MaxText/configs/v5p/README.md new file mode 100644 index 0000000000000000000000000000000000000000..27e001f194aa72e798c51cab04fb4cb7704e1086 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/configs/v5p/README.md @@ -0,0 +1,58 @@ + + +# High Performance Model Configs on TPU v5p +Expected performance results for 32B, 64B, 128B, 256B, 512B, and 1024B parameter models running on TPU v5p: + +### 32B model +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | -----------------: | ------- | +| 1x v5p-128 | 328 | 71.47% | +| 2x v5p-128 | 319 | 69.43% | + +### 64B model +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | -----------------: | ------- | +| 1x v5p-128 | 323 | 70.31% | +| 2x v5p-128 | 309 | 67.26% | + +### 128B model +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | -----------------: | ------- | +| 1x v5p-256 | 315 | 68.68% | +| 2x v5p-256 | 305 | 66.34% | +| 1x v5p-512 | 316 | 68.83% | +| 2x v5p-512 | 274 | 59.66% | + +### 256B model +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | -----------------: | ------- | +| 1x v5p-1024 | 308 | 67.09% | +| 2x v5p-1024 | 289 | 62.99% | + +### 512B model +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | -----------------: | ------- | +| 1x v5p-1024 | 294 | 63.99% | +| 2x v5p-1024 | 282 | 61.45% | + +### 1024B model +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | -----------------: | ------- | +| 1x v5p-2048 | 254 | 55.35% | +| 2x v5p-2048 | 237 | 51.55% | +| 1x v5p-4096 | 297 | 64.80% | +| 2x v5p-4096 | 279 | 60.83% | \ No newline at end of file diff --git a/maxtext-setup/maxtext/MaxText/convert_gemma_chkpt.py b/maxtext-setup/maxtext/MaxText/convert_gemma_chkpt.py new file mode 100644 index 0000000000000000000000000000000000000000..0da08429031357fa322bb1452cd1510f2306834b --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/convert_gemma_chkpt.py @@ -0,0 +1,198 @@ +""" + Copyright 2023 Google LLC + 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. + """ +# pylint: disable=line-too-long +""" +Convert orbax Gemma checkpoint to MaxText compatible checkpoint. +""" + +import jax +import jax.numpy as jnp +import numpy as np +jax.config.update('jax_platform_name', 'cpu') +import argparse +import copy +from flax.training import train_state + +from typing import Any +import sys +import max_logging + + +import orbax + +import checkpointing +from train import save_checkpoint + +Params = dict[str, Any] + +def nest_params(params: Params) -> Params: + """Nests params as a dict of dicts rather than a flat dict.""" + nested_params = {} + for path, param in params.items(): + *path, leaf = path.split('/') + subdict = nested_params + for key in path: + subdict = subdict.setdefault(key, {}) + subdict[leaf] = param + return nested_params + +def main(raw_args=None) -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--base_model_path', type=str, required=True) + parser.add_argument('--maxtext_model_path', type=str, required=True) + parser.add_argument('--model_size', type=str, required=True) + args = parser.parse_args(raw_args) + if args.model_size not in ('2b','7b'): + raise NotImplementedError + + print("Loading checkpoint") + checkpointer = orbax.checkpoint.PyTreeCheckpointer() + params = checkpointer.restore(args.base_model_path) + params = nest_params(params) + num_layers = ( + max(( + int(k.split('_')[1]) + for k in params['transformer'].keys() + if 'layer_' in k + )) + + 1 + ) + hidden_dim, embed_dim = ( + params['transformer']['layer_0']['mlp']['linear']['w'].shape + ) + num_heads, head_dim, _ = ( + params['transformer']['layer_0']['attn']['attn_vec_einsum']['w'].shape + ) + print("Model configurations from checkpoint") + print(f"num_layers: {num_layers}") + print(f"hidden_dim: {hidden_dim}") + print(f"embed_dim: {embed_dim}") + print(f"num_heads: {num_heads}") + print(f"head_dim: {head_dim}") + + jax_weights = { + 'decoder': { + 'decoder_norm': { + 'scale': params['transformer']['final_norm']['scale'] + 1 + }, + }, + 'token_embedder':{ + 'embedding': params['transformer']['embedder']['input_embedding'] * jnp.sqrt(embed_dim) + } + + } + self_attention = dict({ + 'query': { + 'kernel' : [] + }, + 'key': { + 'kernel' : [] + }, + 'value': { + 'kernel' : [] + }, + 'out': { + 'kernel' : [] + }, + }) + + layer_weight = dict({ + 'mlp': { + 'wi_0': { + 'kernel' : [] + }, + 'wi_1': { + 'kernel' : [] + }, + 'wo': { + 'kernel' : [] + }, + }, + 'pre_self_attention_norm': { + 'scale': [] + }, + 'pre_ffw_norm': { + 'scale': [] + }, + }) + + for layer_idx in range(num_layers): + in_layer_name = 'layer_' + str(layer_idx) + # attention block + if args.model_size == '2b': # MQA + self_attention['query']['kernel'].append(params['transformer'][in_layer_name]['attn']['q_einsum']['w'].transpose((1, 0, 2)) * head_dim**-0.5) + self_attention['key']['kernel'].append(params['transformer'][in_layer_name]['attn']['kv_einsum']['w'][0].transpose((1, 0, 2))) + self_attention['value']['kernel'].append(params['transformer'][in_layer_name]['attn']['kv_einsum']['w'][1].transpose((1, 0, 2))) + else: + self_attention['query']['kernel'].append(params['transformer'][in_layer_name]['attn']['qkv_einsum']['w'][0].transpose((1, 0, 2)) * head_dim**-0.5) + self_attention['key']['kernel'].append(params['transformer'][in_layer_name]['attn']['qkv_einsum']['w'][1].transpose((1, 0, 2))) + self_attention['value']['kernel'].append(params['transformer'][in_layer_name]['attn']['qkv_einsum']['w'][2].transpose((1, 0, 2))) + self_attention['out']['kernel'].append(params['transformer'][in_layer_name]['attn']['attn_vec_einsum']['w']) + # mlp + layer_weight['mlp']['wi_0']['kernel'].append(params['transformer'][in_layer_name]['mlp']['gating_einsum']['w'][0]) + layer_weight['mlp']['wi_1']['kernel'].append(params['transformer'][in_layer_name]['mlp']['gating_einsum']['w'][1]) + layer_weight['mlp']['wo']['kernel'].append(params['transformer'][in_layer_name]['mlp']['linear']['w']) + layer_weight['pre_self_attention_norm']['scale'].append(params['transformer'][in_layer_name]['pre_attention_norm']['scale'] + 1) + layer_weight['pre_ffw_norm']['scale'].append(params['transformer'][in_layer_name]['pre_ffw_norm']['scale'] + 1) + + self_attention['query']['kernel'] = np.array(self_attention['query']['kernel']).transpose((1, 0, 2, 3)) + self_attention['key']['kernel'] = np.array(self_attention['key']['kernel']).transpose((1, 0, 2, 3)) + self_attention['value']['kernel'] = np.array(self_attention['value']['kernel']).transpose((1, 0, 2, 3)) + self_attention['out']['kernel'] = np.array(self_attention['out']['kernel']).transpose((1, 0, 2, 3)) + + layer_weight['mlp']['wi_0']['kernel'] = np.array(layer_weight['mlp']['wi_0']['kernel']).transpose((1, 0, 2)) + layer_weight['mlp']['wi_1']['kernel'] = np.array(layer_weight['mlp']['wi_1']['kernel']).transpose((1, 0, 2)) + layer_weight['mlp']['wo']['kernel'] = np.array(layer_weight['mlp']['wo']['kernel']).transpose((1, 0, 2)) + layer_weight['pre_self_attention_norm']['scale'] = np.array(layer_weight['pre_self_attention_norm']['scale']).transpose((1, 0)) + layer_weight['pre_ffw_norm']['scale'] = np.array(layer_weight['pre_ffw_norm']['scale']).transpose((1, 0)) + + layer_weight['self_attention'] = copy.deepcopy(self_attention) + jax_weights['decoder']['layers'] = copy.deepcopy(layer_weight) + jax_weights = jax.tree_map(jnp.array, jax_weights) + def astype_fn(x): + if isinstance(x, jnp.ndarray): + return x.astype(jnp.bfloat16) + else: + return x + jax_weights = jax.tree_map(astype_fn, jax_weights) + + enable_checkpointing=True + async_checkpointing=False + save_interval_steps=1 + + + checkpoint_manager = checkpointing.create_orbax_checkpoint_manager( + args.maxtext_model_path, + enable_checkpointing, + async_checkpointing, + save_interval_steps + ) + + state_new = train_state.TrainState( + step=0, + apply_fn=None, + params=jax_weights, + tx=None, # type: ignore + opt_state={} + ) + + if checkpoint_manager is not None: + if save_checkpoint(checkpoint_manager, 0, state_new): + max_logging.log("saved a checkpoint at step 0") + # Upon preemption, exit when and only when all ongoing saves are complete. + if checkpoint_manager.reached_preemption(0): + checkpoint_manager.wait_until_finished() + sys.exit() + +if __name__ == "__main__": + main() diff --git a/maxtext-setup/maxtext/MaxText/convert_gpt3_ckpt_from_paxml.py b/maxtext-setup/maxtext/MaxText/convert_gpt3_ckpt_from_paxml.py new file mode 100644 index 0000000000000000000000000000000000000000..6318ddd5155f21d790a6073bfb5d5ba6d6b27ad6 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/convert_gpt3_ckpt_from_paxml.py @@ -0,0 +1,233 @@ +""" + Copyright 2023 Google LLC + 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. + """ + +# pylint: disable=line-too-long +"""Convert weights from a paxml gpt3 model to a MaxText one. + +Test cmd for gpt3-52k: +python MaxText/convert_gpt3_ckpt_from_paxml.py \ + --paxml-ckpt-path=gs://maxtext-gpt3/ckpt_test/paxml/checkpoints/checkpoint_00000000/state \ + --maxtext-model-name=gpt3-52k \ + --run-name=$RUN_NAME \ + --base-output-directory=$BASE_OUTPUT_DIR + +True cmd for gpt3-175b: + +The script is memory demanding, requires at least 250 GiB in cpu and cumulative TPU memory of all devices should be + above ~4.2 TiB (175 billion param * 4 byte/param * 3 (model var and 2 opt momentums) * 2 copies in converting) + +python MaxText/convert_gpt3_ckpt_from_paxml.py \ + --paxml-ckpt-path=gs://mlperf-llm-public2/gpt3_spmd1x64x24_tpuv4-3072_v84_20221101/checkpoints/checkpoint_00004000 \ + --maxtext-model-name=gpt3-175b \ + --run-name=$RUN_NAME \ + --base-output-directory=$BASE_OUTPUT_DIR +""" +import max_utils +import optimizers +import pyconfig +import os +from jax import random +from jax.sharding import Mesh +from layers.models import Transformer +from layers import quantizations +import checkpointing + +import numpy as np +import tensorstore as ts + +import sys +import jax +import gc +import max_logging +from psutil import Process +from train import save_checkpoint +import argparse + +def fmt_size(num_bytes: int) -> str: + assert num_bytes > 0 + for unit in ["B", "KiB", "MiB", "GiB"]: + if num_bytes < 1024.0: + break + num_bytes /= 1024.0 + return f"{num_bytes:.2f} {unit}" + +def check_memory(): + """print out cpu/tpu memory.""" + cpu_bytes = Process().memory_info().rss + max_logging.log(f"cpu memory: {fmt_size(cpu_bytes)}") + for d in jax.local_devices(): + stats = d.memory_stats() + used = stats['bytes_in_use'] + limit = stats['bytes_limit'] + max_logging.log(f"tpu memory: Using {fmt_size(used)} / {fmt_size(limit)} ({used/limit:%}) on {d}") + + +def convert(paxml_ckpt_path, maxtext_model_name, base_output_directory, run_name): + """convert ckpt.""" + + base_args = [ + '', 'MaxText/configs/base.yml', # base arg + 'per_device_batch_size=1', + 'ici_fsdp_parallelism=-1', 'ici_tensor_parallelism=1', + f'model_name={maxtext_model_name}', + f'run_name={run_name}', f'base_output_directory={base_output_directory}', + 'checkpoint_period=1', + 'async_checkpointing=false', + ] + pyconfig.initialize(base_args) + cfg = pyconfig.config + init_rng, _ = random.split(random.PRNGKey(cfg.init_weights_seed), 2) + devices_array = max_utils.create_device_mesh(cfg) + mesh = Mesh(devices_array, cfg.mesh_axes) + + quant = quantizations.configure_quantization(cfg) + model = Transformer(cfg, mesh, quant=quant) + learning_rate_schedule = max_utils.create_learning_rate_schedule(cfg) + tx = optimizers.get_optimizer(cfg, learning_rate_schedule) + + checkpoint_manager = checkpointing.create_orbax_checkpoint_manager( + cfg.checkpoint_dir, + cfg.enable_checkpointing, + cfg.async_checkpointing, + cfg.checkpoint_period, + ) + + state, _, _ = max_utils.setup_training_state(model, None, tx, cfg, init_rng, mesh, checkpoint_manager) + max_logging.log("start") + check_memory() + + # maxtext keystr: (paxml keystr, transform_fn) + keystr_map = { + "['token_embedder']['embedding']": (".params.lm.softmax.logits_ffn.linear.w", lambda x: x.T), + "['decoder']['position_embedder']['embedding']": (".params.lm.position_emb.emb_var", None), + "['decoder']['layers']['pre_self_attention_norm']['scale']": (".params.lm.transformer.repeat.sub.x_layers_0.layer_norm.scale", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['layers']['pre_self_attention_norm']['bias']": (".params.lm.transformer.repeat.sub.x_layers_0.layer_norm.bias", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['layers']['self_attention']['query']['kernel']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.combined_qkv.w", lambda x: np.moveaxis(x[:,0], 0, cfg.param_scan_axis)), + "['decoder']['layers']['self_attention']['query']['bias']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.combined_qkv.b", lambda x: np.moveaxis(x[:,0], 0, cfg.param_scan_axis)), + "['decoder']['layers']['self_attention']['key']['kernel']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.combined_qkv.w", lambda x: np.moveaxis(x[:,1], 0, cfg.param_scan_axis)), + "['decoder']['layers']['self_attention']['key']['bias']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.combined_qkv.b", lambda x: np.moveaxis(x[:,1], 0, cfg.param_scan_axis)), + "['decoder']['layers']['self_attention']['value']['kernel']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.combined_qkv.w", lambda x: np.moveaxis(x[:,2], 0, cfg.param_scan_axis)), + "['decoder']['layers']['self_attention']['value']['bias']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.combined_qkv.b", lambda x: np.moveaxis(x[:,2], 0, cfg.param_scan_axis)), + "['decoder']['layers']['self_attention']['qkv_proj']['kernel']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.combined_qkv.w", lambda x: np.moveaxis(x, [2, 0], [0, cfg.param_scan_axis])), + "['decoder']['layers']['self_attention']['qkv_proj']['bias']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.combined_qkv.b", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['layers']['self_attention']['out']['kernel']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.post.w", lambda x: np.moveaxis(x, [0, 1], [cfg.param_scan_axis, -1])), + "['decoder']['layers']['self_attention']['out']['bias']": (".params.lm.transformer.repeat.sub.x_layers_0.self_attention.post.b", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['layers']['mlp']['mlp_layer_norm']['scale']": (".params.lm.transformer.repeat.sub.x_layers_0.ff_layer.layer_norm.scale", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['layers']['mlp']['mlp_layer_norm']['bias']": (".params.lm.transformer.repeat.sub.x_layers_0.ff_layer.layer_norm.bias", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['layers']['mlp']['wi']['kernel']": (".params.lm.transformer.repeat.sub.x_layers_0.ff_layer.ffn_layer1.linear.w", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['layers']['mlp']['wi']['bias']": (".params.lm.transformer.repeat.sub.x_layers_0.ff_layer.ffn_layer1.bias.b", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['layers']['mlp']['wo']['kernel']": (".params.lm.transformer.repeat.sub.x_layers_0.ff_layer.ffn_layer2.linear.w", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['layers']['mlp']['wo']['bias']": (".params.lm.transformer.repeat.sub.x_layers_0.ff_layer.ffn_layer2.bias.b", lambda x: np.moveaxis(x, 0, cfg.param_scan_axis)), + "['decoder']['decoder_norm']['scale']": (".params.lm.final_ln.scale", lambda x: x.T), + "['decoder']['decoder_norm']['bias']": (".params.lm.final_ln.bias", None), + } + + state_map = { + ".step": ("step", None), + ".opt_state.count": ("opt_states_0.no_prefix_0.count", None), + } + + def get_layer_prefix(keystr_pax): + # different path format between decoder_layer variable + if "x_layers_0" in keystr_pax: + # string format for all variables in scanned decoder layer + prefix_pax_opt_state = f"p#{cfg.base_num_decoder_layers}#i-1_2" + else: + prefix_pax_opt_state = "no_prefix_2" + return prefix_pax_opt_state + + for keystr_maxtext, (keystr_pax, transform_fn) in keystr_map.items(): + # model variable + state_map[f".params{keystr_maxtext}"] = (f"mdl_vars{keystr_pax}", transform_fn) + prefix_pax_opt_state = get_layer_prefix(keystr_pax) + # first momentum in optimizer state + state_map[f".opt_state.mu{keystr_maxtext}"] = (f"opt_states_0.{prefix_pax_opt_state}.m{keystr_pax}", transform_fn) + # second momentum in optimizer state + state_map[f".opt_state.nu{keystr_maxtext}"] = (f"opt_states_0.{prefix_pax_opt_state}.v{keystr_pax}", transform_fn) + + def verify_fn(key_path, _): + keystr = jax.tree_util.keystr(key_path) + assert keystr in state_map, f"{keystr} not found" + + jax.tree_util.tree_map_with_path(verify_fn, state) + + memory_metrics = {'max_cpu_bytes': 0} + + bucket_name, paxml_ckpt_prefix = paxml_ckpt_path[len("gs://"):].split('/', 1) + + def map_fn(key_path, value): + key_path_str = jax.tree_util.keystr(key_path) + file_path, transform_fn = state_map[key_path_str] + full_path = os.path.join(paxml_ckpt_prefix, file_path) + spec = {'driver': 'zarr', 'metadata_key': '.zarray', 'kvstore': {}} + spec['kvstore'] = { + 'bucket': bucket_name, + 'driver': 'gcs', + 'path': full_path, + } + + arr = ts.open(ts.Spec(spec), open=True).result().read().result() + if transform_fn is not None: + arr = transform_fn(arr) + + assert value.shape == arr.shape, f"{key_path}, {value.shape}, {arr.shape}" + shape = value.shape + sharding = value.sharding + result = jax.make_array_from_single_device_arrays( + shape, + sharding, + [jax.device_put(np.array(arr[index]), d) + for d, index in sharding.addressable_devices_indices_map(shape).items()], + ) + + # log peak cpu memory + cpu_bytes = Process().memory_info().rss + memory_metrics["max_cpu_bytes"] = max(cpu_bytes, memory_metrics["max_cpu_bytes"]) + + # collect cpu memory back asap + arr = None + del arr + gc.collect() + max_logging.log(f"{key_path_str} finished") + check_memory() + return result + + converted_state = jax.tree_util.tree_map_with_path(map_fn, state) + max_logging.log("converted state finished") + check_memory() + + if save_checkpoint(checkpoint_manager, converted_state.step, converted_state): + max_logging.log(f"saved a checkpoint at step {converted_state.step}") + # Upon preemption, exit when and only when all ongoing saves are complete. + if checkpoint_manager.reached_preemption(converted_state.step): + checkpoint_manager.wait_until_finished() + sys.exit() + + max_logging.log(f"Peak cpu memory in a single process: {fmt_size(memory_metrics['max_cpu_bytes'])}") + max_logging.log("checkpoint converted and saved successfully.") + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('--paxml-ckpt-path', + type=str, + default="gs://mlperf-llm-public2/gpt3_spmd1x64x24_tpuv4-3072_v84_20221101/checkpoints/checkpoint_00004000", + required=True) + parser.add_argument('--maxtext-model-name', choices=['gpt3-175b', 'gpt3-52k'], type=str, required=True) + parser.add_argument('--base-output-directory', type=str, required=True) + parser.add_argument('--run-name', type=str, required=True) + + args = parser.parse_args() + if not args.paxml_ckpt_path.startswith("gs://"): + raise ValueError("--paxml-ckpt-path should be a gcs path starting with gs://") + + convert(args.paxml_ckpt_path, args.maxtext_model_name, args.base_output_directory, args.run_name) diff --git a/maxtext-setup/maxtext/MaxText/decode.py b/maxtext-setup/maxtext/MaxText/decode.py new file mode 100644 index 0000000000000000000000000000000000000000..1003d77015483a0aafb1666cb5b1fb9799f3a5d1 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/decode.py @@ -0,0 +1,75 @@ +# Copyright 2024 Google LLC +# +# 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. + +'''CLI Utility for Running Inference on a Single Stream''' + +import jax + +import maxengine +from jetstream.engine import token_utils + +import os +import pyconfig +import sys + + +def main(config): + engine = maxengine.MaxEngine(config) + params = engine.load_params() + + text = config.prompt + metadata = engine.get_tokenizer() + vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids) + tokenizer = vocab.tokenizer + tokens, true_length = token_utils.tokenize_and_pad(text, vocab, is_bos=True, + prefill_lengths=[config.max_prefill_predict_length]) + assert tokens.size <= config.max_prefill_predict_length, "can't take too many tokens" + + prefill_result = engine.prefill( + params=params, padded_tokens=tokens, true_length=true_length + ) + slot=0 + + decode_state = engine.init_decode_state() + decode_state = engine.insert( + prefill_result, decode_state, slot=slot + ) + + steps = range(config.max_prefill_predict_length, config.max_target_length) + sampled_tokens_list = [] + for _ in steps: + decode_state, sampled_tokens = engine.generate( + params, decode_state + ) + sampled_tokens_list.append(sampled_tokens) + + results = [sampled_tokens.get_result_at_slot(slot).tokens.item() for sampled_tokens in sampled_tokens_list] + output = tokenizer.detokenize(results) + print(f"Input `{text}` -> `{output}`") + + if config.autoregressive_decode_assert != "": + assert output==config.autoregressive_decode_assert, \ + f"generated text mismatch {output=} {config.autoregressive_decode_assert=}" + +def validate_config(config): + assert config.load_full_state_path == "", "Decode doesn't operate on full states! Convert to parameter checkpoint first."\ + "Using generate_param_only_checkpoint." + +if __name__ == "__main__": + jax.config.update('jax_default_prng_impl', 'unsafe_rbg') + os.environ["TF_CPP_MIN_LOG_LEVEL"] = "0" + pyconfig.initialize(sys.argv) + cfg = pyconfig.config + validate_config(cfg) + main(cfg) diff --git a/maxtext-setup/maxtext/MaxText/generate_param_only_checkpoint.py b/maxtext-setup/maxtext/MaxText/generate_param_only_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..1691164173d67743b3ceabd306d50368c9203832 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/generate_param_only_checkpoint.py @@ -0,0 +1,142 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=g-bad-todo, abstract-method, consider-using-with, ungrouped-imports +"""Trasforms a "full state" including optimzer state to a bfloat16 "parameter state" without optimizer state. + This typically used for turning a state output by training.py into a state than can be consumed by decode.py. + + The input "fullstate" is passed in via: + load_full_state_path. + The output "parameter state" is output to the checkpoint directory. Additionally it is cast down to bf16. +""" + +import checkpointing +import jax +import max_logging +import max_utils +import optimizers +import pyconfig + +from absl import app +from etils import epath +from jax.sharding import Mesh +from jax import random +from typing import Sequence +from layers import models, quantizations +from train import save_checkpoint + +Transformer = models.Transformer + +def _possibly_unroll_params(config, training_state, training_state_annotations, mesh): + """ If input layers are scanned, and force_unroll is set, + return modify training_state and train_state_annotations to be "unrolled". + Otherwise do nothing.""" + if not config.scan_layers or not config.force_unroll: + return + + training_state_layers = training_state.params['decoder']['layers'] + training_state_annotations_layers = training_state_annotations.params['decoder']['layers'] + + def new_pspec(x): + return jax.sharding.PartitionSpec(*x[0:config.param_scan_axis] + x[config.param_scan_axis+1:]) + + new_per_layer_state_annotation = jax.tree_map(new_pspec, training_state_annotations_layers) + new_per_layer_state_sharding = jax.tree_map(lambda x : jax.sharding.NamedSharding(mesh, x), new_per_layer_state_annotation) + + for i in range(config.num_decoder_layers): + def slice_ith(input_layers): + return jax.tree_map(lambda x : jax.numpy.take(x, i, axis = config.param_scan_axis), input_layers) + + new_layer = jax.jit(slice_ith, out_shardings = new_per_layer_state_sharding)(training_state_layers) + + training_state.params['decoder'][f'layers_{i}'] = new_layer + training_state_annotations.params['decoder'][f'layers_{i}'] = new_per_layer_state_annotation + + del training_state.params['decoder']['layers'] + del training_state_annotations.params['decoder']['layers'] + + jax.tree_map(lambda x : x.delete(), training_state_layers) + +def _read_train_checkpoint(config, checkpoint_manager, mesh): + """Read training checkpoint at path defined by load_full_state_path.""" + # Model and Optimizer definition + quant = quantizations.configure_quantization(config) + model = Transformer(config, mesh, quant) + rng = random.PRNGKey(0) + learning_rate_schedule = max_utils.create_learning_rate_schedule(config) + tx = optimizers.get_optimizer(config, learning_rate_schedule) + state, state_mesh_notations, _ = max_utils.setup_training_state( + model, None, tx, config, rng, mesh, checkpoint_manager + ) + num_params = max_utils.calculate_num_params_from_pytree(state.params) + max_logging.log(f"In input checkpoint Number of model params={num_params/1e9:.3f} billion") + return state, state_mesh_notations + +def _save_decode_checkpoint(config, state, checkpoint_manager): + """Generate checkpoint for decode from the training_state.""" + with jax.spmd_mode('allow_all'): + decode_state = max_utils.init_decode_state(None, jax.tree_map(lambda x : x.astype(jax.numpy.bfloat16), state.params)) + if checkpoint_manager is not None: + if save_checkpoint(checkpoint_manager, 0, decode_state): + max_logging.log(f"saved an decode checkpoint at {config.checkpoint_dir}") + checkpoint_manager.wait_until_finished() + +def generate_decode_checkpoint(config): + """ + Generate an decode checkpoint from a given training checkpoint. + - Training checkpoint is loaded from config.load_full_state_path. + - Inference checkpoint will be saved at the config's checkpoint directory. + """ + + devices_array = max_utils.create_device_mesh(config) + mesh = Mesh(devices_array, config.mesh_axes) + + assert config.checkpoint_dir, "checkpoint_dir not configured" + # Remove any old checkpoint + path = epath.Path(config.checkpoint_dir) + if path.exists(): + if jax.process_index() == 0: + path.rmtree() + + # Create a checkpoint manager to save decode checkpoint at config.checkpoint_dir + checkpoint_manager = checkpointing.create_orbax_checkpoint_manager( + config.checkpoint_dir, + config.enable_checkpointing, + config.async_checkpointing, + config.checkpoint_period, + ) + # Read training state from config.load_paramaters_path + max_logging.log(f"Read training checkpoint from: {config.load_full_state_path}") + training_state, training_state_annotations = _read_train_checkpoint(config, checkpoint_manager, mesh) + assert training_state.opt_state != {}, "missing opt_state in training checkpoint" + + _possibly_unroll_params(config, training_state, training_state_annotations, mesh) + + # Save decode state to config's checkpoint directory at step 0 + max_logging.log(f"Save decode checkpoint at: {config.checkpoint_dir}") + _save_decode_checkpoint(config, training_state, checkpoint_manager) + max_logging.log(f"Successfully generated decode checkpoint at: {config.checkpoint_dir}0/items") + return True + + +def main(argv: Sequence[str]) -> None: + print(argv) + pyconfig.initialize(argv) + generate_decode_checkpoint(pyconfig.config) + + +if __name__ == "__main__": + app.run(main) diff --git a/maxtext-setup/maxtext/MaxText/inference_microbenchmark.py b/maxtext-setup/maxtext/MaxText/inference_microbenchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..ec46b137f7c2caaac4329f2feefc2c6d0072a30c --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/inference_microbenchmark.py @@ -0,0 +1,195 @@ +""" + Copyright 2024 Google LLC + + 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. + """ + +"""Inference microbenchmark for prefill and autoregressive steps.""" +import datetime +import jax +import json +import sys + +from jetstream.engine import token_utils +import max_utils +import maxengine +import maxtext_utils +import pyconfig + + +def summarize_pytree_data(params, name="Params"): + """ Generate basic metrics of a given Pytree. """ + num_params, total_param_size, avg_param_size = max_utils.summarize_size_from_pytree(params) + num_params_in_billions = num_params / 1e9 + total_param_size_in_gb = total_param_size / 1e9 + print(f"{name} stats: \n" + f"\tTotal number of params: {num_params_in_billions:.3f} billion \n" + f"\tTotal memory usage: {total_param_size_in_gb:.3f} GB \n" + f"\tAvg size: {avg_param_size:.3f} bytes\n") + return num_params, total_param_size, avg_param_size + + +def prefill_benchmark_loop(config, engine, decode_state, params, tokens, true_length, iters, profile_name=""): + """ Inner loop for benchmarking prefill step. """ + max_utils.activate_profiler(config, profile_name) + start = datetime.datetime.now() + for i in range(iters): + slot = int(i % (jax.device_count() * config.per_device_batch_size)) + prefill_result = engine.prefill(params=params, padded_tokens=tokens, true_length=true_length) + decode_state = engine.insert(prefill_result, decode_state, slot=slot) + jax.block_until_ready(decode_state) + end = datetime.datetime.now() + max_utils.deactivate_profiler(config) + return (end - start).total_seconds(), decode_state + + +def prefill_benchmark(config, engine, params, decode_state, tokens, true_length, + iters=100, profile_name="", num_model_params=None): + """ Handles init, warmup, running prefill benchmark, and printing results. """ + if num_model_params is None: + num_model_params, _, _ = summarize_pytree_data(params, name="Params") + + prefill_result = engine.prefill(params=params, padded_tokens=tokens, true_length=true_length) + decode_state = engine.insert(prefill_result, decode_state, slot=0) + jax.block_until_ready(decode_state) + prefill_result = engine.prefill(params=params, padded_tokens=tokens, true_length=true_length) + decode_state = engine.insert(prefill_result, decode_state, slot=0) + jax.block_until_ready(decode_state) + + print(f"Prefill results for length {tokens.size}:\n") + + profile_name = f"prefill_{tokens.size}" if profile_name == "" else profile_name + time_in_s, decode_state = prefill_benchmark_loop(config, engine, decode_state, params, tokens, true_length, iters, + profile_name=profile_name) + prefill_average_ms = 1000 * time_in_s / iters + total_prefill_tflops, _, _ = maxtext_utils.calculate_tflops_prefill(num_model_params, tokens.size, config) + tflops_per_sec_per_device = total_prefill_tflops / jax.device_count() / prefill_average_ms * 1000. + print(f"\tPrefill step average time: {prefill_average_ms:.3f}ms\n" + f"\tPrefill total TFLOPs: {total_prefill_tflops:.3f}\n" + f"\tPrefill TFLOPs/sec/device: {tflops_per_sec_per_device:.3f}\n\n\n\n") + result_dict = {"prefill_time_in_ms": prefill_average_ms, + "prefill_total_tflops": total_prefill_tflops, + "prefill_tflops_per_sec_per_device": tflops_per_sec_per_device} + return result_dict, decode_state + + +def ar_benchmark_loop(config, engine, decode_state, params, iters, profile_name=""): + """ Inner loop for benchmarking ar step. """ + max_utils.activate_profiler(config, profile_name) + start = datetime.datetime.now() + for _ in range(iters): + decode_state, _ = engine.generate(params, decode_state) + jax.block_until_ready(decode_state) + end = datetime.datetime.now() + max_utils.deactivate_profiler(config) + return (end - start).total_seconds(), decode_state + + +def ar_benchmark(config, engine, params, decode_state, cache_size=None, model_size=None, profile_name="", iters=100): + """ Handles init, warmup, running ar benchmark, and printing results. """ + if cache_size is None: + _, cache_size, _ = summarize_pytree_data(decode_state['cache'], name="Cache") + if model_size is None: + _, model_size, _ = summarize_pytree_data(params, name="Params") + global_batch_size = jax.device_count() * config.per_device_batch_size + + # Warmup + decode_state, _ = engine.generate(params, decode_state) + jax.block_until_ready(decode_state) + decode_state, _ = engine.generate(params, decode_state) + jax.block_until_ready(decode_state) + + profile_name = "autoregress" if profile_name == "" else profile_name + time_in_s, decode_state = ar_benchmark_loop(config, engine, decode_state, params, profile_name=profile_name, iters=iters) + seconds_per_step = time_in_s / iters + ar_average_ms = seconds_per_step*1000 + total_throughput = jax.device_count() * config.per_device_batch_size / seconds_per_step + + GB_per_step_per_device = (model_size + cache_size) / 1e9 / jax.device_count() + bw_per_device = GB_per_step_per_device/seconds_per_step + print(f"AutoRegressive results:\n" + f"\tAR step average time: {ar_average_ms:.3f}ms\n" + f"\tAR step average time per seq: {ar_average_ms/global_batch_size:.3f}ms\n" + f"\tAR global batch size: {global_batch_size}\n" + f"\tAR throughput: {total_throughput:.3f} tokens/second\n" + f"\tAR memory bandwidth per device: {bw_per_device:.3f} GB/s\n\n\n") + + + result_dict = {"ar_step_in_ms": ar_average_ms, + "ar_step_in_ms_per_seq": ar_average_ms / global_batch_size, + "ar_global_batch_size": global_batch_size, + "ar_total_throughput_tokens_per_second": total_throughput, + "ar_device_bandwidth_GB_per_second": bw_per_device} + return result_dict, decode_state + + +def collate_results(config, results, model_size, cache_size, num_model_params, incl_config=False): + """ Adds model/cache size info and optionally config info to results. """ + results["sizes"] = { + "Model_size_in_GB": model_size / 1e9, + "cache_size_in_GB": cache_size / 1e9, + "model_params_in_billions": num_model_params / 1e9, + } + if incl_config: + results["config"] = {} + for k, v in dict(config.get_keys()).items(): + results["config"][k] = str(v) if k == "dtype" else v # json fails with original dtype + return results + + +def write_results(results, filename=""): + if filename != "": + with open(filename, "w", encoding="utf-8") as f: + json.dump(results, f, indent=2) + + +def print_results_for_analyze(results): + prefill_bucket_size_to_ms = {} + for k, v in results["Prefill"].items(): + prefill_bucket_size_to_ms[int(k)] = round(v["prefill_time_in_ms"], 3) + print("\nFor usage in analyze_sharegpt.py :") + print(f"PREFILL_BUCKET_SIZE_TO_MS = {prefill_bucket_size_to_ms}") + print(f"SYSTEM_TIME_PER_DECODE_TOKEN_MS = {results['AutoRegressive']['ar_step_in_ms_per_seq']}") + + +def main(config): + engine = maxengine.MaxEngine(config) + params = engine.load_params() + prefill_lengths = [64, 128, 256, 512, 1024] + benchmark_loop_iters = 10 + text = config.prompt + metadata = engine.get_tokenizer() + vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids) + + decode_state = engine.init_decode_state() + _, cache_size, _ = summarize_pytree_data(decode_state['cache'], name="Cache") + num_model_params, model_size, _ = summarize_pytree_data(params, name="Model") + + benchmark_results = {"Prefill": {}} + benchmark_results["AutoRegressive"], decode_state = ar_benchmark( + config, engine, params, decode_state, iters=benchmark_loop_iters, cache_size=cache_size, model_size=model_size) + for prefill_length in prefill_lengths: + tokens, true_length = token_utils.tokenize_and_pad( + text, vocab, is_bos=True, prefill_lengths=[prefill_length]) + benchmark_results["Prefill"][prefill_length], decode_state = prefill_benchmark( + config, engine, params, decode_state, tokens, true_length, + iters=benchmark_loop_iters, num_model_params=num_model_params) + + results = collate_results(config, benchmark_results, model_size, cache_size, num_model_params) + write_results(results, filename="") + print_results_for_analyze(results) + + +if __name__ == "__main__": + pyconfig.initialize(sys.argv) + main(pyconfig.config) diff --git a/maxtext-setup/maxtext/MaxText/inference_scratch/analyze_sharegpt.py b/maxtext-setup/maxtext/MaxText/inference_scratch/analyze_sharegpt.py new file mode 100644 index 0000000000000000000000000000000000000000..47d8715cfd13aa0e228adc814d2a4728982a24bd --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/inference_scratch/analyze_sharegpt.py @@ -0,0 +1,108 @@ +# Copyright 2024 Google LLC +# +# 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 json + +PREFILL_BUCKET_SIZE_TO_MS = {64: 9.174, 128: 11.087, 256: 18.468, 512: 29.128, 1024: 58.386} +SYSTEM_TIME_PER_DECODE_TOKEN_MS = 0.32591875 +MAX_INPUT_TOKENS = 1024 +MAX_OUTPUT_TOKENS = 1024 + +def next_power_of_2(x): + return 1 if x == 0 else 2**(x - 1).bit_length() + +def tokens_in_input_str(s): + return_val = int(1.3 * len(s.split())) + return return_val + +def get_prefill_and_generate_times(filename=""): + if filename == "": + return PREFILL_BUCKET_SIZE_TO_MS, SYSTEM_TIME_PER_DECODE_TOKEN_MS + + prefill_bucket_size_to_ms = {} + with open(filename, "r") as f: + microbenchmark_results = json.load(f) + for k, v in microbenchmark_results["Prefill"].items(): + prefill_bucket_size_to_ms[int(k)] = round(v["prefill_time_in_ms"], 3) + + return prefill_bucket_size_to_ms, microbenchmark_results['AutoRegressive']['ar_step_in_ms_per_seq'] + +def get_conversations_from_file(filename, max_input_tokens, max_output_tokens): + convo_token_numbers = [] + with open(filename, 'r') as f: + loaded_share_gpt = json.load(f) + for example in loaded_share_gpt: + if len(example['conversations']) < 2: + continue + num_input_tokens = tokens_in_input_str(example['conversations'][0]['value']) + num_output_tokens = tokens_in_input_str(example['conversations'][1]['value']) + convo_token_numbers.append((num_input_tokens, num_output_tokens)) + + num_convos = len(convo_token_numbers) + kept_convos = [c for c in convo_token_numbers if c[0] <= max_input_tokens and c[1] <= max_output_tokens] + + mean_input = sum(c[0] for c in kept_convos) / len(kept_convos) + mean_output = sum(c[1] for c in kept_convos) / len(kept_convos) + + print(f"Kept {len(kept_convos)} of {num_convos} total convos. {len(100*kept_convos)/num_convos:.3f}%") + print(f"Out of kept convos, mean input tokens: {mean_input:.3f}, mean output tokens: {mean_output:.3f}") + return kept_convos + + +def compute_times(convos, prefill_bucket_size_to_ms, system_time_per_decode_token_ms, verbose=False): + total_prefill_system_ms = 0 + total_generate_system_ms = 0 + for convo in convos: + input_tok, output_tok = convo + bucket = max(128, next_power_of_2(input_tok)) + generate_system_ms = output_tok * system_time_per_decode_token_ms + prefill_system_ms = prefill_bucket_size_to_ms[bucket] + total_prefill_system_ms += prefill_system_ms + total_generate_system_ms += generate_system_ms + if verbose: + print(f"{convo} {bucket}, {prefill_system_ms:.2f}, {generate_system_ms:.2f}") + + total_prefill_time_seconds = total_prefill_system_ms / 1000 + total_generate_time_seconds = total_generate_system_ms / 1000 + total_time_s = total_prefill_time_seconds + total_generate_time_seconds + + print(f"\nTotal time {total_time_s:.3f} seconds: " + f"\n\tPrefill time: {total_prefill_time_seconds:.3f} seconds" + f"\n\tGenerate time: {total_generate_time_seconds:.3f} seconds") + return total_time_s, total_prefill_time_seconds, total_generate_time_seconds + + +def get_num_tokens_in_convos(convos): + num_input_tokens = sum(c[0] for c in convos) + num_output_tokens = sum(c[1] for c in convos) + return num_input_tokens, num_output_tokens + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('convo_file', type=str, + help='a json file containing conversations') + parser.add_argument('-t', '--mb_timing_file', type=str, default="", + help='a json file containing microbenchmark timing results') + parser.add_argument('-v', '--verbose', action="store_true") + args = parser.parse_args() + + convos = get_conversations_from_file(args.convo_file, MAX_INPUT_TOKENS, MAX_OUTPUT_TOKENS) + total_input_tokens, total_output_tokens = get_num_tokens_in_convos(convos) + prefill_time_ms_buckets, generate_time_ms = get_prefill_and_generate_times(filename=args.mb_timing_file) + total_time_seconds, _, _ = compute_times(convos, prefill_time_ms_buckets, generate_time_ms, args.verbose) + + print(f"Output {total_output_tokens} tokens in {total_time_seconds:.3f} seconds " + f"= {total_output_tokens/total_time_seconds:.3f} out tok/s") diff --git a/maxtext-setup/maxtext/MaxText/inference_scratch/gemma_7b.sh b/maxtext-setup/maxtext/MaxText/inference_scratch/gemma_7b.sh new file mode 100644 index 0000000000000000000000000000000000000000..8a2994d1bea07b256ac19faa33b3dc7176bd6c06 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/inference_scratch/gemma_7b.sh @@ -0,0 +1,8 @@ +export M_LOAD_PARAMETERS_PATH=gs://runner-maxtext-logs/reroll5/checkpoints/10/items/ +export M_PER_DEVICE_BATCH_SIZE=24 +export M_MAX_PREFILL_PREDICT_LENGTH=1024 +export M_MAX_TARGET_LENGTH=2048 + +#python MaxText/decode.py MaxText/configs/base.yml tokenizer_path=assets/tokenizer.gemma run_name=runner_2024-03-06-04-17 steps=10 weight_dtype=bfloat16 async_checkpointing=false model_name=gemma-7b ici_fsdp_parallelism=1 ici_autoregressive_parallelism=-1 scan_layers=false + +python MaxText/maxengine_server.py MaxText/configs/base.yml tokenizer_path=assets/tokenizer.gemma run_name=runner_2024-03-06-04-17 steps=10 weight_dtype=bfloat16 async_checkpointing=false model_name=gemma-7b ici_fsdp_parallelism=1 ici_autoregressive_parallelism=-1 scan_layers=false diff --git a/maxtext-setup/maxtext/MaxText/inference_scratch/run_inference_microbenchmark.sh b/maxtext-setup/maxtext/MaxText/inference_scratch/run_inference_microbenchmark.sh new file mode 100644 index 0000000000000000000000000000000000000000..c8447679674c17d187fe611e676ddc5c8add82d6 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/inference_scratch/run_inference_microbenchmark.sh @@ -0,0 +1,18 @@ +# llama2-7b +python MaxText/inference_microbenchmark.py \ +MaxText/configs/base.yml \ +async_checkpointing=false \ +attention=autoselected \ +dataset_path=gs://maxtext-dataset \ +ici_fsdp_parallelism=1 \ +ici_autoregressive_parallelism=-1 \ +max_prefill_predict_length=1024 \ +max_target_length=2048 \ +per_device_batch_size=16 \ +quantization=int8 \ +quantize_kvcache=True \ +steps=10 \ +scan_layers=false \ +model_name=llama2-7b \ +weight_dtype=bfloat16 \ +tokenizer_path=assets/tokenizer.llama2 diff --git a/maxtext-setup/maxtext/MaxText/inference_utils.py b/maxtext-setup/maxtext/MaxText/inference_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..786ecaae79e31b77bf49b1c14727f14e7aa38f1f --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/inference_utils.py @@ -0,0 +1,81 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +import jax +import jax.numpy as jnp + +NEG_INF = -1.0e7 # Masking purpose + + +# pylint: disable=bare-except, consider-using-generator +""" Common Maxtext inference utilities. These seem like they should be a library. + + Inspired by an Google-internal implementation, Global Vision Transformer. +""" + +def sampling(logits, rng, algorithm, topk=0, nucleus_topp=0, temperature=1.0): + """ + logits: unnormalized logits to sample, shaped [YOUR_LEADING_DIMS, Vocab], before logit + rng: rng key to use + algorithm: string representing supported algorithms + topk: restricting to topk logits before sampling + nucleus_topp: restricting to p probability mass before sampling + temperature: temperature parameter for scaling probability + """ + if algorithm == "greedy": + return jnp.argmax(logits, axis=-1) + elif algorithm == "weighted": + return jax.random.categorical(rng, logits / temperature) + elif algorithm == "nucleus": + return sample_nucleus_topp_logits(logits, nucleus_topp, temperature, rng) + elif algorithm == "topk": + return sample_topk_logits(logits, topk, temperature, rng) + else: + raise ValueError(f"Sampling {algorithm=} not supported!") + +def sample_nucleus_topp_logits(logits, nucleus_topp, temperature, rng): + """Restrict sampling to the top logits with cumulative probability >= nucleus_topp. + + The nucleus sampling method is proposed in the paper `The Curious Case of + Neural Text Degeneration (https://arxiv.org/pdf/1904.09751.pdf)` + + """ + if nucleus_topp < 0: + raise ValueError("Can't apply nucleus with parameter {nucleus_topp=} less zero") + logits_sorted = jnp.sort(logits, axis=-1)[..., ::-1] # sort descending + sorted_cum_probs = jnp.cumsum( + jax.nn.softmax(logits_sorted, axis=-1), axis=-1) # get cumsum probs + cutoff_index = jnp.sum( + sorted_cum_probs < nucleus_topp, axis=-1, keepdims=True) # find cutoff index + cutoff_logit = jnp.take_along_axis(logits_sorted, cutoff_index, axis=-1) + logits = jnp.where(logits < cutoff_logit, + jnp.full_like(logits, NEG_INF), logits) + return jax.random.categorical(rng, logits / temperature) + +def sample_topk_logits(logits, topk, temperature, rng): + """ Restricting sampling to the best k logits. """ + if topk <= 0: + raise ValueError("Can't apply algorithm topk with parameter {topk=} less than or equal to zero") + topk_logits, topk_idxs = jax.lax.top_k(logits, topk) + topk_token = jnp.expand_dims( + jax.random.categorical(rng, topk_logits/temperature).astype(jnp.int32), + axis=-1) + sampled_tokens = jnp.squeeze( + jnp.take_along_axis(topk_idxs, topk_token, axis=-1), + axis=-1).astype(jnp.int32) + return sampled_tokens + + diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_grain_data_processing.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_grain_data_processing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aa08553d3678f26bd5972010783baf8bb2de342 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_grain_data_processing.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_grain_operations.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_grain_operations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..486231852984e0c706f3e6a000efd5a59b0b8e07 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_grain_operations.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_grain_tokenizer.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_grain_tokenizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d203e19f6fb324305de4e2b36085bf7e10c34caf Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_grain_tokenizer.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_tfds_data_processing.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_tfds_data_processing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25130f7e2fc8bd640c90580d1b5f290d2c074aed Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_tfds_data_processing.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_tfds_data_processing_c4_mlperf.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_tfds_data_processing_c4_mlperf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e98725bcd23fd7d27f2d3445922f81563105049 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/_tfds_data_processing_c4_mlperf.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/input_pipeline_interface.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/input_pipeline_interface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f51ebbcbf52d6bc0182717968fd16b50f9f1deca Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/input_pipeline/__pycache__/input_pipeline_interface.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/_grain_data_processing.py b/maxtext-setup/maxtext/MaxText/input_pipeline/_grain_data_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..47af07f6f5098391fc7adb79a8090939d3cccccf --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/input_pipeline/_grain_data_processing.py @@ -0,0 +1,169 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Input pipeline using Grain.""" + +import os +import re +from typing import Optional + +import ml_collections +import jax +import grain.python as grain + +import tokenizer +from input_pipeline import _grain_operations +from input_pipeline import _grain_tokenizer + +import multihost_dataloading + +def get_datasets( + config: ml_collections.ConfigDict +): + """Load dataset from array_record files for using with grain""" + data_dir = os.path.join(config.dataset_path, config.dataset_name) + train_files = [data_dir + '/' + f for f in os.listdir(data_dir) if re.match(r'.*train.*', f)] + train_ds = grain.ArrayRecordDataSource(train_files) + if config.eval_dataset_name: + eval_files = [data_dir + '/' + f for f in os.listdir(data_dir) if re.match(rf'.*{config.eval_split}.*', f)] + eval_ds = grain.ArrayRecordDataSource(eval_files) + else: + eval_ds = train_ds + + return train_ds, eval_ds + +def preprocess_dataset(config: ml_collections.ConfigDict, + global_mesh, + train_ds, eval_ds, + vocab_path: Optional[str] = None, + data_shuffle_seed = 0, + add_bos = True, + add_eos = True + ): + """Use grain to pre-process the dataset and return iterators""" + # Set global batch size. + global_batch_size_to_load = config.global_batch_size_to_load + + if config.eval_per_device_batch_size > 0: + eval_batch_size = config.eval_per_device_batch_size * global_mesh.size + else: + eval_batch_size = global_batch_size_to_load + + train_iter = preprocessing_pipeline( + train_ds, + vocab_path, + add_bos, + add_eos, + config.grain_worker_count, + global_batch_size_to_load, + global_mesh, + shuffle=config.enable_data_shuffling, + num_epochs=1, + pack_examples=True, + max_length=config.max_target_length, + data_shuffle_seed=data_shuffle_seed,) + + eval_iter = preprocessing_pipeline( + eval_ds, + vocab_path, + add_bos, + add_eos, + config.grain_worker_count, + eval_batch_size, + global_mesh, + shuffle=config.enable_data_shuffling, + pack_examples=True, + max_length=config.max_target_length, + data_shuffle_seed=data_shuffle_seed,) + + predict_iter = preprocessing_pipeline( + eval_ds, + vocab_path, + add_bos, + add_eos, + config.grain_worker_count, + eval_batch_size, + global_mesh, + shuffle=config.enable_data_shuffling, + pack_examples=True, + max_length=config.max_target_length, + data_shuffle_seed=data_shuffle_seed) + + return train_iter, eval_iter, predict_iter + +def preprocessing_pipeline( + dataset, + vocab_path, + add_bos: bool, + add_eos: bool, + grain_worker_count: int, + batch_size: int, + global_mesh, + shuffle: bool, + num_epochs: Optional[int] = 1, + pack_examples: bool = True, + max_length: int = 512, + shift: bool = True, + drop_remainder: bool = True, + data_shuffle_seed = 0, +): + """Apply grain operations to preprocess the given dataset.""" + assert ( + batch_size % global_mesh.size == 0 + ), 'Batch size should be divisible number of global devices.' + + operations = [] + operations.append(_grain_operations.ParseFeatures()) + operations.append(_grain_operations.NormalizeFeatures()) + operations.append(_grain_tokenizer.TokenizeAndTrim(["inputs","targets"], + max_length, vocab_path, + add_bos, add_eos)) + + # Pack and Batch examples. + if pack_examples: + operations.append(grain.experimental.PackAndBatchOperation( + batch_size=batch_size // jax.process_count(), + length_struct={'inputs':max_length,'targets':max_length})) + operations.append(_grain_operations.ReformatPacking()) + else: + operations.append(_grain_operations.PadToMaxLength(max_length)) + operations.append(grain.Batch(batch_size=batch_size // jax.process_count(), drop_remainder=drop_remainder)) + + # Shift inputs for teacher-forced training + if shift: + operations.append(_grain_operations.ShiftData(axis=1)) + + index_sampler = grain.IndexSampler( + num_records=len(dataset), + num_epochs = num_epochs, + shard_options=grain.ShardOptions( + shard_index = jax.process_index(), shard_count = jax.process_count(), drop_remainder = True + ), + shuffle = shuffle, + seed = data_shuffle_seed + ) + + dataloader = grain.DataLoader( + data_source = dataset, + operations = operations, + sampler = index_sampler, + worker_count=grain_worker_count, + ) + + multihost_gen = multihost_dataloading.MultiHostDataLoadIterator(dataloader, global_mesh) + + # Return multi-host jax.Array prep iterator + return multihost_gen diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/_grain_operations.py b/maxtext-setup/maxtext/MaxText/input_pipeline/_grain_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..25508376b061825acf93b3bcaf8ce566215999ce --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/input_pipeline/_grain_operations.py @@ -0,0 +1,116 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Operations used by Grain""" + +import dataclasses +from typing import Dict +import grain.python as grain +import numpy as np +import tensorflow as tf +Features = Dict[str, tf.Tensor] + +@dataclasses.dataclass +class ParseFeatures(grain.MapTransform): + """Parse serialized example""" + def map(self, features): + def _parse(example): + parsed = tf.io.parse_example( + example, { + 'text': tf.io.FixedLenFeature(shape=(), dtype=tf.string) + }) + return parsed + return _parse(features) + + +@dataclasses.dataclass +class NormalizeFeatures(grain.MapTransform): + """Normalize text feature keys.""" + def map(self, features): + return { + 'inputs':features['text'].numpy().decode(), + 'targets': features['text'].numpy().decode() + } + + +@dataclasses.dataclass +class ReformatPacking(grain.MapTransform): + """Reformat packing outputs.""" + def map(self, data): + return{ + 'inputs':data[0]['inputs'], + 'targets':data[0]['targets'], + 'inputs_segmentation':data[1]['inputs'], + 'targets_segmentation':data[1]['targets'], + 'inputs_position':data[2]['inputs'], + 'targets_position':data[2]['targets'], + } + + +@dataclasses.dataclass +class PadToMaxLength(grain.MapTransform): + """Pads each input to the specified length""" + def __init__(self, max_length): + self.max_length = max_length + def map(self, data): + """map to each element""" + def _pad(x, max_length): + pad_amount = max(max_length - x.shape[0], 0) + pad_amount = [(0, pad_amount)] + [(0, 0)] * (len(x.shape) - 1) + return np.pad(x, pad_amount) + data['inputs_segmentation'] = np.ones(data['inputs'].shape, dtype = np.int32) + data['inputs_position'] = np.arange(data['inputs'].shape[0], dtype = np.int32) + data['targets_segmentation'] = np.ones(data['targets'].shape, dtype = np.int32) + data['targets_position'] = np.arange(data['targets'].shape[0], dtype = np.int32) + for key, _ in data.items(): + data[key] = _pad(data[key], self.max_length) + return data + + +def shift_right(x, axis=1): + """Shift the input to the right by padding and slicing on axis.""" + pad_widths = [(0, 0)] * len(x.shape) + pad_widths[axis] = (1, 0) + slices = [slice(None),] * len(x.shape) + slices[axis] = slice(0, -1) + padded = np.pad( + x, + pad_widths, + mode='constant', + constant_values=x.dtype.type(0) + ) + return padded[tuple(slices)] + +def shift_and_refine(x, axis=1): + """Shift inputs, set segmentation to 0 when target element is 0. + Replace EOS by 0 for packed inputs.""" + x['inputs'] = shift_right(x['inputs'], axis=axis) + targets_nonzero = x['targets'] != 0 + x['inputs_segmentation'] *= targets_nonzero + x['targets_segmentation'] *= targets_nonzero + # For packed targets, the first shifted token of a new sequence is made + # 0, rather than being the EOS token for the last sequence. + x['inputs'] *= x['inputs_segmentation'] == shift_right(x['inputs_segmentation'], axis=axis) + + return x + +@dataclasses.dataclass +class ShiftData(grain.MapTransform): + """Shift inputs and refine annotations.""" + def __init__(self, axis = 1): + self.axis = axis + def map(self, data): + return shift_and_refine(data, axis=self.axis) diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/_grain_tokenizer.py b/maxtext-setup/maxtext/MaxText/input_pipeline/_grain_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e9436799a14166f7af9fb38ed446a8afef23d201 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/input_pipeline/_grain_tokenizer.py @@ -0,0 +1,78 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Tokenize Op used by Grain""" + +from collections.abc import Sequence +import dataclasses +import threading +from typing import Any +from sentencepiece import SentencePieceProcessor +import grain.python as grain +import numpy as np + +@dataclasses.dataclass +class TokenizeAndTrim(grain.MapTransform): + """Tokenize and trim features to sequence length.""" + # pylint: disable=attribute-defined-outside-init + feature_names: str | Sequence[str] + sequence_length: int | Sequence[int] + model_path: str + add_bos: bool + add_eos: bool + + def __post_init__(self): + self._processor = None + self._initialize_processor_lock = threading.Lock() + if isinstance(self.feature_names, str): + self.feature_names = [self.feature_names] + if isinstance(self.sequence_length, int): + self.sequence_length = [self.sequence_length] * len(self.feature_names) + + def map(self, features: dict[str, Any]) -> dict[str, Any]: + """Maps to each element.""" + if self._processor is None: + with self._initialize_processor_lock: + if self._processor is None: # Ensures only one thread initializes SPP. + self._processor = SentencePieceProcessor() + self._processor.Load(self.model_path) + for feature_name, sequence_length in zip( + self.feature_names, self.sequence_length, strict=True + ): + text = features[feature_name] + token_ids = self._processor.EncodeAsIds(text) + if self.add_bos: + token_ids = [self._processor.bos_id()] + token_ids + + if self.add_eos: + token_ids = token_ids[:sequence_length-1] + token_ids = token_ids + [self._processor.eos_id()] + else: + token_ids = token_ids[:sequence_length] + + features[feature_name] = np.asarray(token_ids, dtype=np.int32) + return features + + def __getstate__(self): + state = self.__dict__.copy() + del state["_processor"] + del state["_initialize_processor_lock"] + return state + + def __setstate__(self, state): + self.__dict__.update(state) + self._processor = None + self._initialize_processor_lock = threading.Lock() diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/_tfds_data_processing.py b/maxtext-setup/maxtext/MaxText/input_pipeline/_tfds_data_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..051a1e8b95ec596f12aaa91fe4f256cfb0fe1c03 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/input_pipeline/_tfds_data_processing.py @@ -0,0 +1,258 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Input pipeline for a LM1B dataset.""" + +import os +from typing import Optional + +import ml_collections +import tensorflow as tf +import tensorflow_datasets as tfds +import jax + +import multihost_dataloading +import tokenizer +import sequence_packing + +AUTOTUNE = tf.data.experimental.AUTOTUNE + + +# Right-shifting token inputs for teacher-forced training. +# ----------------------------------------------------------------------------- + +def shift_right_tf(x, axis=1): + """Shift the input to the right by padding and slicing on axis.""" + pad_widths = [(0, 0)] * len(x.shape) + pad_widths[axis] = (1, 0) + slices = [slice(None),] * len(x.shape) + slices[axis] = slice(0, -1) + padded = tf.pad( + x, + tf.constant(pad_widths), + mode='constant', + constant_values=tf.constant(0, x.dtype)) + return padded[tuple(slices)] + + +def shift_inputs_tf(x, segment_ids=None, axis=1): + """Shift inputs and replace EOS by 0 for packed inputs.""" + shifted = shift_right_tf(x, axis=axis) + # For packed targets, the first shifted token of a new sequence is made + # 0, rather than being the EOS token for the last sequence. + if segment_ids is not None: + shifted *= tf.cast( + segment_ids == shift_right_tf(segment_ids, axis=axis), x.dtype + ) + return shifted + +def shift_data(x, axis=0, segmented=True): + segment_ids = x['inputs_segmentation'] if segmented else None + x['inputs'] = shift_inputs_tf(x['inputs'], segment_ids=segment_ids, axis=axis) + return x + +def shift_data_by_truncation(x): + x['inputs'] = x['inputs'][:-1] + x['targets'] = x['targets'][1:] + return x + + +def normalize_features(ds): + """Normalize text feature keys.""" + def _normalize_features(features): + features['inputs'] = features.pop('text') + features['targets'] = features['inputs'] + return features + + return ds.map( + _normalize_features, + num_parallel_calls=AUTOTUNE) + +def length_trim(ds, max_len): + """"Trim to Max length""" + def _trim_fn(features): + if tf.shape(features['inputs'])[0] > max_len: + features['inputs'] = features['inputs'][:max_len] + if tf.shape(features['targets'])[0] > max_len: + features['targets'] = features['targets'][:max_len] + return features + + return ds.map( + _trim_fn, + num_parallel_calls=AUTOTUNE + ) + +# ----------------------------------------------------------------------------- +# Main dataset preparation. +# ----------------------------------------------------------------------------- + + +def preprocessing_pipeline( + dataset, + batch_size: int, + global_mesh, + shuffle: bool, + num_epochs: Optional[int] = 1, + pack_examples: bool = True, + shuffle_buffer_size: int = 1024, + max_length: int = 512, + shift: bool = True, + drop_remainder: bool = True, + prefetch_size = tf.data.experimental.AUTOTUNE, + data_shuffle_seed = 0, +): + """Shuffle and batch/pack the given dataset.""" + + def truncate_to_max_allowable_length(x, max_length): + x['inputs'] = x['inputs'][:max_length] + x['targets'] = x['targets'][:max_length] + return x + + + if max_length > 0: + # We can take upto max_length+1 because there would be truncation by 1 token + # for both inputs and targets + dataset = dataset.map(lambda x: truncate_to_max_allowable_length(x, max_length+1)) + + # Shuffle and repeat. + if shuffle: + dataset = dataset.shuffle(shuffle_buffer_size, seed = data_shuffle_seed) + + dataset = dataset.repeat(num_epochs) + + + # Shift inputs for teacher-forced training + if shift: + dataset = dataset.map( + shift_data_by_truncation, + num_parallel_calls=tf.data.AUTOTUNE, + deterministic=True) + + # Perform greedy sequence packing + if pack_examples: + dataset = sequence_packing.pack_dataset(dataset, max_length) + assert ( + batch_size % global_mesh.size == 0 + ), 'Batch size should be divisible number of global devices.' + + # Batch examples. + if pack_examples: + dataset = dataset.batch(batch_size // jax.process_count(), drop_remainder=drop_remainder) + else: + # simple (static-shape) padded batching + dataset = dataset.padded_batch( + batch_size // jax.process_count(), + padded_shapes={'inputs': max_length, 'targets': max_length}, + padding_values={'inputs': 0, 'targets': 0}, + drop_remainder=drop_remainder) + + if prefetch_size: + dataset = dataset.prefetch(prefetch_size) + + multihost_gen = multihost_dataloading.MultiHostDataLoadIterator(dataset, global_mesh) + + # Return multi-host jax.Array prep iterator + return multihost_gen + + +def get_datasets( + config: ml_collections.ConfigDict, + read_config = None, +): + """Load and return dataset of batched examples for use during training.""" + # Training dataset. + train_ds_builder = tfds.builder(config.dataset_name) + # train_data = get_raw_dataset(train_ds_builder, 'train') + train_ds = train_ds_builder.as_dataset(split='train', + read_config = read_config, + shuffle_files=config.enable_data_shuffling) + # shard the dataset as soon as it is loaded + train_ds = train_ds.shard(num_shards = jax.process_count(), index = jax.process_index()) + train_ds = normalize_features(train_ds) + + # Evaluation dataset. + if config.eval_dataset_name: + eval_ds_builder = tfds.builder(config.eval_dataset_name) + else: + eval_ds_builder = train_ds_builder + # eval_data = get_raw_dataset(eval_ds_builder, config.eval_split) + eval_ds = eval_ds_builder.as_dataset(split=config.eval_split, + read_config = read_config, + shuffle_files=False) + eval_ds = eval_ds.shard(num_shards = jax.process_count(), index = jax.process_index()) + eval_ds = normalize_features(eval_ds) + + return train_ds, eval_ds + +def preprocess_dataset(config: ml_collections.ConfigDict, + global_mesh, + train_ds, eval_ds, sp_tokenizer, + data_shuffle_seed = 0, + ): + """Pre-process the dataset and return iterators""" + # Tokenize data. + train_ds = train_ds.map( + tokenizer.TokenizeOp(sp_tokenizer), num_parallel_calls=AUTOTUNE) + eval_ds = eval_ds.map( + tokenizer.TokenizeOp(sp_tokenizer), num_parallel_calls=AUTOTUNE) + + # Set global batch size. + global_batch_size_to_load = config.global_batch_size_to_load + + if config.eval_per_device_batch_size > 0: + eval_batch_size = config.eval_per_device_batch_size * global_mesh.size + else: + eval_batch_size = global_batch_size_to_load + + def filter_keys(record): + return {'inputs': record['inputs'], 'targets': record['targets']} + train_ds = train_ds.map(filter_keys,num_parallel_calls=tf.data.AUTOTUNE) + eval_ds = eval_ds.map(filter_keys,num_parallel_calls=tf.data.AUTOTUNE) + + train_iter = preprocessing_pipeline( + train_ds, + global_batch_size_to_load, + global_mesh, + shuffle=config.enable_data_shuffling, + num_epochs=None, + pack_examples=True, + max_length=config.max_target_length, + shift=True, + data_shuffle_seed = data_shuffle_seed,) + + eval_iter = preprocessing_pipeline( + eval_ds, + eval_batch_size, + global_mesh, + shuffle=False, + pack_examples=False, + max_length=config.max_target_length, + shift=False, + drop_remainder=False, + data_shuffle_seed = data_shuffle_seed,) + + predict_iter = preprocessing_pipeline( + eval_ds, + eval_batch_size, + global_mesh, + shuffle=config.enable_data_shuffling, + pack_examples=False, + max_length=config.max_target_length, + shift=False, + drop_remainder=False, + data_shuffle_seed = data_shuffle_seed,) + + return train_iter, eval_iter, predict_iter diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/_tfds_data_processing_c4_mlperf.py b/maxtext-setup/maxtext/MaxText/input_pipeline/_tfds_data_processing_c4_mlperf.py new file mode 100644 index 0000000000000000000000000000000000000000..dc423643a8a34acb1e297a31ffc5ec97bfe4fa89 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/input_pipeline/_tfds_data_processing_c4_mlperf.py @@ -0,0 +1,276 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Input pipeline for gpt3 c4 mlperf dataset.""" + +from typing import Optional + +import functools + +import numpy as np + +import ml_collections +import tensorflow as tf +import tensorflow_datasets as tfds +import jax +import jax.numpy as jnp +from jax.experimental import multihost_utils + +import tokenizer +import multihost_dataloading +import sequence_packing + +AUTOTUNE = tf.data.experimental.AUTOTUNE + +# data processing functions: +# _shift_left_and_pad, rekey, reduce_concat_tokens and split_tokens_to_targets_length +# Adapted from: +# https://github.com/google-research/text-to-text-transfer-transformer/blob/ba171b6f94eafcee60d0714fd6d60749b572d1f2/t5/data/preprocessors.py +# ----------------------------------------------------------------------------- +def _shift_left_and_pad(tensor, pad_val): + """Shift the input to the left with pad_val""" + # Expand dims here so that the below code can work with 1-d tensors. + v = tf.expand_dims(tensor, 0) + # Make sure we keep tensor as ragged to allow for uneven concat. + if isinstance(v, tf.Tensor): + v = tf.RaggedTensor.from_tensor(v) + + # Append padding to the last item of every sequence. + pad_shape = tf.concat([v.bounding_shape()[:-2], [1, 1]], axis=0) + pad_tensor = tf.broadcast_to(pad_val, pad_shape) + last_in_sequence = tf.concat([v[..., -1:, 1:], pad_tensor], axis=-1) + # Concat back the newly modified final sequence item. + v = tf.concat([v[..., :-1, :], last_in_sequence], axis=-2) + # Un-expand outer dimension. + v = v[0] + return v + +def rekey(ds, key_map=None): + """normalization with key mapping""" + def _rekey(x, key_map=None): + """Replace the feature keys according to the mapping in `key_map`. + For example, if the dataset returns examples of the format: + {'foo': 'something', 'bar': 'something else', 'zoo': 'others'} + and key_map = {'boo': 'foo', 'spar': 'bar', 'zoo': None} then this function will return + examples with the format + {'boo': 'something', 'spar': 'something else'} + If a mapping is to None, then the key will be dropped. + Args: + x: an example to process. + key_map: dictionary mapping new keys to original keys + Returns: + A preprocessed example with the format listed above. + """ + if key_map: + return { + new_key: x[old_key] + for new_key, old_key in key_map.items() if old_key + } + return x + + return ds.map( + functools.partial(_rekey, key_map=key_map), + num_parallel_calls=AUTOTUNE) + +def reduce_concat_tokens(dataset, + feature_key='targets', + batch_size=128, + ): + """Token-preprocessor to concatenate multiple unrelated documents. + If we want to generate examples of exactly the right length, + (to avoid wasting space on padding), then we use this function, folowed by + split_tokens. + Args: + dataset: a tf.data.Dataset with dictionaries containing the key feature_key. + feature_key: an string + batch_size: an integer - how many documents to concatenate into one + Returns: + a dataset + """ + dataset = dataset.map( + lambda x: {feature_key: x[feature_key]}, num_parallel_calls=AUTOTUNE) + dataset = dataset.padded_batch(batch_size, padded_shapes={feature_key: [-1]}) + def _my_fn(x): + tokens = tf.reshape(x[feature_key], [-1]) + # strip padding + tokens = tf.boolean_mask(tokens, tf.cast(tokens, tf.bool)) + return {feature_key: tokens} + + return dataset.map(_my_fn, num_parallel_calls=AUTOTUNE) + +def split_tokens(dataset, + max_tokens_per_segment=128, + feature_key='targets', + ): + """Split examples into multiple examples each. + The intended use case is to break up long examples for use in unsupervised + transfer-learning. + This function is generally preceded by select_random_chunk. + Args: + dataset: a tf.data.Dataset with dictionaries containing the key feature_key. + max_tokens_per_segment: an integer, the maximum number of tokens in each + segment. Only the final segment may be shorter. + feature_key: a string, the feature to split + Returns: + a dataset + """ + def _split_tokens(x): + """Split one token sequence into multiple multiple.""" + tokens = x[feature_key] + n_tokens = tf.size(tokens) + length = max_tokens_per_segment + + # Pad to a multiple of length, then use tf.reshape to split up the tokens + # into num_segments segments each of the given length. + num_segments = tf.cast( + tf.math.ceil(tf.cast(n_tokens, tf.float32) / tf.cast(length, tf.float32)), + tf.int32) + padding = num_segments * length - tf.size(tokens) + tokens = tf.pad(tokens, [[0, padding]]) + return tf.reshape(tokens, [-1, length]) + + def _strip_padding(x): + return {feature_key: tf.boolean_mask(x, tf.cast(x, tf.bool))} + + # Filter empty examples. + dataset = dataset.filter(lambda x: tf.not_equal(tf.size(x[feature_key]), 0)) + dataset = dataset.map(_split_tokens, num_parallel_calls=AUTOTUNE) + dataset = dataset.unbatch() + return dataset.map( + _strip_padding, num_parallel_calls=AUTOTUNE) + +def split_tokens_to_targets_length(dataset, sequence_length): + return split_tokens(dataset, max_tokens_per_segment=sequence_length) + +def _pad_to_batch_size(ds: tf.data.Dataset, batch_size: int, num_examples: Optional[int] = None,) -> tf.data.Dataset: + """Pad unevenly distributed eval data in each shard with new entries to multiples of batch size.""" + + # local_num represents the total number of examples in eval dataset, + if num_examples: + local_num = num_examples + else: + def _get_num_examples(ds: tf.data.Dataset) -> int: + # Iterate one-by-one instead of len(list(...)) to reduce peak memory. + num_examples = 0 + for _ in ds: + num_examples += 1 + + return num_examples + + local_num = _get_num_examples(ds) + local_num_batches = (local_num + batch_size - 1) // batch_size + # Find the max number of batches required across all Jax processes. + num_batches_all = multihost_utils.process_allgather( + jnp.array([local_num_batches]), tiled=False) + num_batches = np.max(num_batches_all) + + pad_num = num_batches * batch_size - local_num + assert pad_num >= 0 + print( + f'Eval data has {local_num} local entries, padding now with ' + f'{pad_num} extra entries to get {num_batches} batches.') + # Repeat a random example to make the last batch full. + def _add_pad(x): + x['targets_segmentation'] *= 0 + return x + pad_ds = ds.take(1).map(_add_pad).repeat(pad_num) + return ds.concatenate(pad_ds) + +def get_datasets( + config: ml_collections.ConfigDict, +): + """Load and return dataset of batched examples for use during training.""" + # Training dataset. + read_config = tfds.ReadConfig( + shuffle_seed = config.data_shuffle_seed, + ) + train_ds_builder = tfds.builder(config.dataset_name) + train_ds = train_ds_builder.as_dataset(split='train2', read_config=read_config, shuffle_files=config.enable_data_shuffling) + + eval_ds_builder = tfds.builder(config.eval_dataset_name) + eval_ds = eval_ds_builder.as_dataset(split='validation_tokenized_5662seqs', read_config=read_config, shuffle_files=False) + + # shard the dataset as soon as it is loaded + train_ds = train_ds.shard(num_shards = jax.process_count(), index = jax.process_index()) + train_ds = rekey(train_ds, {'inputs': None, 'targets': 'text'}) + + eval_ds = eval_ds.shard(num_shards = jax.process_count(), index = jax.process_index()) + # note validation_tokenized_5662seqs split is pre tokenized, reduce_concated and splitted to target_length + # mainly to avoid eval sequences change depending on the number of hosts + eval_ds = rekey(eval_ds, {'inputs': None, 'targets': 'ids'}) + + return train_ds, eval_ds + +def preprocess_dataset(config: ml_collections.ConfigDict, + global_mesh, + train_ds, eval_ds, sp_tokenizer, + data_shuffle_seed: int = 0, + shuffle_buffer_size: int = 128, + ): + """Pre-process the dataset and return iterators for mlperf training.""" + # tokenize + train_ds = train_ds.map( + tokenizer.TokenizeOp(sp_tokenizer, data_keys=('targets',)), num_parallel_calls=AUTOTUNE) + + train_ds = reduce_concat_tokens(train_ds, feature_key='targets', batch_size=4096) + train_ds = split_tokens_to_targets_length(train_ds, config.max_target_length) + train_ds = train_ds.shuffle(shuffle_buffer_size, seed=data_shuffle_seed) + + # note eval_ds is pre tokenized, reduce_concated and splitted to target_length + # mainly to avoid eval sequences change depending on the number of hosts + train_ds = sequence_packing.pack_dataset(train_ds, config.max_target_length) + eval_ds = sequence_packing.pack_dataset(eval_ds, config.max_target_length) + + def format_fn(x, eos_id: int = 1, pad_id: int = 0): + x["inputs"] = x["targets"] + x["inputs_position"] = x["targets_position"] + x["targets"] = _shift_left_and_pad(x["targets"], eos_id) + x["inputs_segmentation"] = tf.where( + tf.logical_and(x["targets"] != eos_id, x["targets"] != pad_id), + x["targets_segmentation"], 0) + x["targets_segmentation"] = x["inputs_segmentation"] + return x + + train_ds = train_ds.map(format_fn, num_parallel_calls=AUTOTUNE) + eval_ds = eval_ds.map(format_fn, num_parallel_calls=AUTOTUNE) + + # Set global batch size. + global_batch_size_to_load = config.global_batch_size_to_load + + if config.eval_per_device_batch_size > 0: + eval_batch_size = config.eval_per_device_batch_size * global_mesh.size + else: + eval_batch_size = global_batch_size_to_load + + train_ds = train_ds.batch(global_batch_size_to_load // jax.process_count(), drop_remainder=True) + + # ensure array split in an equal division for each device + # pad zeros up to the same batch_size among all processes + eval_ds = _pad_to_batch_size(eval_ds, eval_batch_size // jax.process_count()) + eval_ds = eval_ds.batch(eval_batch_size // jax.process_count(), drop_remainder=False) + # We are running eval over exactly one epoch. + # We explicitly cache the entire epoch (in memory) to ensure that it is the + # same across different iterations. + eval_ds = eval_ds.cache() + + train_ds = train_ds.prefetch(AUTOTUNE) + eval_ds = eval_ds.prefetch(AUTOTUNE) + + train_multihost_gen = multihost_dataloading.MultiHostDataLoadIterator(train_ds, global_mesh) + eval_multihost_gen = multihost_dataloading.MultiHostDataLoadIterator(eval_ds, global_mesh) + + # Return multi-host jax.Array prep iterator + return train_multihost_gen, eval_multihost_gen diff --git a/maxtext-setup/maxtext/MaxText/input_pipeline/input_pipeline_interface.py b/maxtext-setup/maxtext/MaxText/input_pipeline/input_pipeline_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..d58d21d5547a4d48174812c90551745c6a29f67e --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/input_pipeline/input_pipeline_interface.py @@ -0,0 +1,148 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Input pipeline""" + +import os + +import tensorflow_datasets as tfds +import jax +import jax.numpy as jnp +from jax.sharding import PartitionSpec as P + +from input_pipeline import _tfds_data_processing +from input_pipeline import _grain_data_processing +from input_pipeline import _tfds_data_processing_c4_mlperf +import tokenizer + +def get_tokenizer(tokenizer_path, add_bos=True, add_eos=True): + # Load tokenizer + sp_tokenizer = tokenizer.load_tokenizer(tokenizer_path=tokenizer_path, + add_bos=add_bos, + add_eos=add_eos) + return sp_tokenizer + +def make_c4_mlperf_train_iterator_and_tokenizer(config, mesh, add_bos, add_eos): + """ Make train iterator and tokenizer for customized C4 dataset for mlperf gpt3 training.""" + train_ds, eval_ds = _tfds_data_processing_c4_mlperf.get_datasets( + config=config, + ) + sp_tokenizer = get_tokenizer(config.tokenizer_path, add_bos, add_eos) + train_iter, eval_iter = _tfds_data_processing_c4_mlperf.preprocess_dataset( + config, + mesh, + train_ds, eval_ds, sp_tokenizer, + data_shuffle_seed=config.data_shuffle_seed + ) + return train_iter, eval_iter, sp_tokenizer + +def make_c4_train_iterator_and_tokenizer(config, mesh, add_bos, add_eos): + """ Make train iterator and tokenizer for C4 dataset""" + read_config = tfds.ReadConfig( + shuffle_seed = config.data_shuffle_seed, + ) + train_ds, eval_ds = _tfds_data_processing.get_datasets( + config=config, + read_config = read_config, + ) + sp_tokenizer = get_tokenizer(config.tokenizer_path, add_bos, add_eos) + train_iter, _, _ = _tfds_data_processing.preprocess_dataset( + config, + mesh, + train_ds, eval_ds, sp_tokenizer, + data_shuffle_seed = config.data_shuffle_seed, + ) + return train_iter, None, sp_tokenizer + +def make_grain_train_iterator_and_tokenizer(config, mesh, add_bos, add_eos): + """ Make train iterator and tokenizer for C4 dataset""" + train_ds, eval_ds = _grain_data_processing.get_datasets( + config=config + ) + sp_tokenizer = get_tokenizer(config.tokenizer_path, add_bos, add_eos) + train_iter, _, _ = _grain_data_processing.preprocess_dataset( + config, + mesh, + train_ds, eval_ds, + vocab_path=config.tokenizer_path, + data_shuffle_seed = config.data_shuffle_seed, + add_bos = add_bos, + add_eos = add_eos + ) + return train_iter, None, sp_tokenizer + +class SyntheticDataIterator(): + """Creates a synthetic data iterator for performance testing work""" + def __init__(self, config, mesh): + self.mesh = mesh + self.config = config + data_pspec = P(*config.data_sharding) + data_pspec_shardings = jax.tree_map( + lambda p: jax.sharding.NamedSharding(mesh, p), data_pspec) + self.data_generator = jax.jit(SyntheticDataIterator.raw_generate_synthetic_data, + out_shardings=data_pspec_shardings, + static_argnums=0) + + def __iter__(self): + return self + + def __next__(self): + with self.mesh: + return self.data_generator(self.config) + + @staticmethod + def raw_generate_synthetic_data(config): + """Generates a single batch of syntehtic data""" + output = {} + output['inputs'] = jax.numpy.zeros( (config.global_batch_size_to_load, config.max_target_length), + dtype=jax.numpy.int32) + output['inputs_position'] = jax.numpy.zeros( (config.global_batch_size_to_load, config.max_target_length), + dtype=jax.numpy.int32) + output['inputs_segmentation'] = jax.numpy.ones( (config.global_batch_size_to_load, config.max_target_length), + dtype=jax.numpy.int32) + output['targets'] = jax.numpy.zeros( (config.global_batch_size_to_load, config.max_target_length), + dtype=jax.numpy.int32) + output['targets_position'] = jax.numpy.zeros( (config.global_batch_size_to_load, config.max_target_length), + dtype=jax.numpy.int32) + output['targets_segmentation'] = jax.numpy.ones( (config.global_batch_size_to_load, config.max_target_length), + dtype=jax.numpy.int32) + return output + +def create_data_iterator_with_tokenizer(config, mesh, add_bos = True, add_eos = True): + if config.dataset_type == "synthetic": + return SyntheticDataIterator(config, mesh), None, get_tokenizer(config.tokenizer_path, add_bos, add_eos) + elif config.dataset_type == "c4": + return make_c4_train_iterator_and_tokenizer(config, mesh, add_bos, add_eos) + elif config.dataset_type == "c4-array_record": + return make_grain_train_iterator_and_tokenizer(config, mesh, add_bos, add_eos) + elif config.dataset_type == "c4_mlperf": + print("Overwrite both add_bos and add_eos to False") + return make_c4_mlperf_train_iterator_and_tokenizer(config, mesh, add_bos=False, add_eos=False) + else: + assert False, "dataset type not implemented" + +def get_shaped_batch(config): + """ Return the shape of the batch - this is what eval_shape would return for the + output of create_data_iterator_with_tokenizer, but eval_shape doesn't work, see b/306901078.""" + batch_shape = (config.global_batch_size_to_load, config.max_target_length) + shaped_batch = {} + shaped_batch['inputs'] = jax.ShapeDtypeStruct(batch_shape, jnp.int32) + shaped_batch['inputs_position'] = jax.ShapeDtypeStruct(batch_shape, jnp.int32) + shaped_batch['inputs_segmentation'] = jax.ShapeDtypeStruct(batch_shape, jnp.int32) + shaped_batch['targets'] = jax.ShapeDtypeStruct(batch_shape, jnp.int32) + shaped_batch['targets_position'] = jax.ShapeDtypeStruct(batch_shape, jnp.int32) + shaped_batch['targets_segmentation'] = jax.ShapeDtypeStruct(batch_shape, jnp.int32) + return shaped_batch diff --git a/maxtext-setup/maxtext/MaxText/layers/__pycache__/attentions.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/layers/__pycache__/attentions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2dd64c85fcd64d385bec43c94226bb276ab83b98 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/layers/__pycache__/attentions.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/layers/__pycache__/embeddings.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/layers/__pycache__/embeddings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88315db10731028a7bc7fceea4cfe29e54540abb Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/layers/__pycache__/embeddings.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/layers/__pycache__/initializers.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/layers/__pycache__/initializers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0df359cd7a9173145fcacc0df42b4cb81edd3991 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/layers/__pycache__/initializers.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/layers/__pycache__/linears.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/layers/__pycache__/linears.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ddae08fe1af1b96766f12f060edca50a45347f8 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/layers/__pycache__/linears.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/layers/__pycache__/mistral.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/layers/__pycache__/mistral.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78c7c6e5694586d7412a24a71c9247fed717fd9f Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/layers/__pycache__/mistral.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/layers/__pycache__/models.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/layers/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..774a233440e482281971e7ae99c8d067a105ca2b Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/layers/__pycache__/models.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/layers/__pycache__/normalizations.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/layers/__pycache__/normalizations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6169ec7be4b80576afedbb4fba605faaf05f2999 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/layers/__pycache__/normalizations.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/layers/__pycache__/quantizations.cpython-310.pyc b/maxtext-setup/maxtext/MaxText/layers/__pycache__/quantizations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b24d0bfbee213fe71f5f3a79b438af0bd01dea68 Binary files /dev/null and b/maxtext-setup/maxtext/MaxText/layers/__pycache__/quantizations.cpython-310.pyc differ diff --git a/maxtext-setup/maxtext/MaxText/layers/attentions.py b/maxtext-setup/maxtext/MaxText/layers/attentions.py new file mode 100644 index 0000000000000000000000000000000000000000..05145c5abd011b2b1bc74495ea6bfd79a79295eb --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/attentions.py @@ -0,0 +1,964 @@ +# Copyright 2023 Google LLC +# +# 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. + +"""Attentions Layers.""" + +import functools +import math +from typing import Optional, Sequence + +from flax import linen as nn +import jax +from jax import lax +from jax import random +from jax.ad_checkpoint import checkpoint_name +from jax.experimental import shard_map +from jax.experimental.pallas.ops import attention as pallas_attention +from jax.experimental.pallas.ops.tpu.splash_attention import splash_attention_mask +from jax.experimental.pallas.ops.tpu.splash_attention import splash_attention_kernel +import jax.numpy as jnp + +import common_types +from layers import embeddings +from layers import initializers +from layers import linears +from layers import quantizations + + +Array = common_types.Array +Config = common_types.Config +DType = common_types.DType +Mesh = common_types.Mesh +PRNGKey = common_types.PRNGKey + +DenseGeneral = linears.DenseGeneral +RotaryEmbedding = embeddings.RotaryEmbedding +NdInitializer = initializers.NdInitializer +Quant = quantizations.AqtQuantization + +AxisNames = common_types.AxisNames +BATCH = common_types.BATCH +LENGTH = common_types.LENGTH +HEAD = common_types.HEAD +D_KV = common_types.D_KV +DEFAULT_MASK_VALUE = -0.7 * float(jnp.finfo(jnp.dtype("float32")).max) + + +nd_dense_init = initializers.nd_dense_init +shard_map = shard_map.shard_map + +dynamic_vector_slice_in_dim = jax.vmap( + lax.dynamic_slice_in_dim, in_axes=(None, 0, None, None)) + +# pylint: disable=line-too-long, g-doc-args, g-doc-return-or-yield, bad-continuation, g-inconsistent-quotes +# pytype: disable=attribute-error + + +def apply_mask_to_logits(logits: Array, mask: Array): + """Applies a floating-point mask to a set of logits. + + The mask is represented as a tensor with some dtype where 0 represents true and values + below a large negative number (here set to + get_large_negative_number(logits.dtype) / 2) represent false. Applying the mask + leaves the logits alone in the true case and replaces them by + get_large_negative_number(logits.dtype) in the false case. Previously, this was + done by adding the logits to the mask; however, this leads to a bad fusion + decision in the compiler that saves the values in memory rather than + just the predicate. This implementation avoids that problem. + + from https://github.com/google/praxis/blob/4712a6b9ee13e224b86e235ff55f7c6bab9fbab3/praxis/py_utils.py#L706 + + Args: + logits: A JTensor of logit values. + mask: A JTensor of mask values with the encoding described in the + function documentation. + + Returns: + Masked logits. + """ + return jnp.where((mask >= DEFAULT_MASK_VALUE * 0.5), logits, DEFAULT_MASK_VALUE) + +def _maybe_aqt_einsum(quant: Quant): + """Maybe overwrite dot general with aqt_dot_general.""" + return jnp.einsum if quant is None else quant.einsum() + +class AttentionOp(nn.Module): + mesh: Mesh + attention_kernel: str + max_target_length: int + num_query_heads: int + num_kv_heads: int + float32_qk_product: bool = False + max_prefill_predict_length: int = -1 + float32_logits: bool = False + flash_axis_names: AxisNames = (BATCH, HEAD, LENGTH, D_KV) + dropout_rate: float = 0. + dtype: DType = jnp.float32 + quant: Optional[Quant] = None + quantize_kvcache: bool = False + + def check_attention_inputs( + self, + query: Array, + key: Array, + value: Array) -> None: + """Check attention inputs.""" + + assert key.ndim == value.ndim, 'k, v must have same rank.' + assert query.shape[:-3] == key.shape[:-3] == value.shape[:-3], ( + 'q, k, v batch dims must match.') + assert key.shape[-2] == value.shape[-2], ('k, v num_kv_heads must match.') + assert key.shape[-3] == value.shape[-3], 'k, v lengths must match.' + assert query.shape[-1] == key.shape[-1], 'q, k depths must match.' + + # Following Pallas MHA Flash Attention Reference. + # https://github.com/google/jax/blob/main/jax/experimental/pallas/ops/tpu/flash_attention.py + # This mask models (1) separate sequences (decoder_segment_ids) and (2) causality + def generate_attention_mask( + self, + query, + key, + decoder_segment_ids: Array | None, + model_mode: str + ) -> Array | None: + mask = None + if model_mode == common_types.MODEL_MODE_AUTOREGRESSIVE: + mask = decoder_segment_ids[:, None, None, None, :] == common_types.DECODING_ACTIVE_SEQUENCE_INDICATOR + elif decoder_segment_ids is not None: + mask = decoder_segment_ids[:, :, None] == decoder_segment_ids[:, None, :] + mask = mask[:, None, None,:, :] + + causal_mask = None + # We enforce causality except for AUTOREGRESSION + if model_mode != common_types.MODEL_MODE_AUTOREGRESSIVE: + _, q_seq_len, _, _ = query.shape + _, kv_seq_len, _, _ = key.shape + mask_shape = (q_seq_len, kv_seq_len) + row_ids = jax.lax.broadcasted_iota(jnp.int32, mask_shape, 0) + col_ids = jax.lax.broadcasted_iota(jnp.int32, mask_shape, 1) + causal_mask = (col_ids <= row_ids)[None, None, None, :, :] + + if (mask is not None) and (causal_mask is not None): + output_mask = jnp.logical_and(mask, causal_mask) + elif mask is not None: + output_mask = mask + elif causal_mask is not None: + output_mask = causal_mask + else: + output_mask = None + + return jnp.where(output_mask, 0.0, DEFAULT_MASK_VALUE) if output_mask is not None else None + + def apply_attention(self, + query: Array, + key: Array, + value: Array, + decoder_segment_ids: Array | None, + model_mode: str): + self.check_attention_inputs(query, key, value) + length = query.shape[-3] + if self.attention_kernel == 'dot_product' or\ + (self.attention_kernel == 'autoselected' and model_mode == common_types.MODEL_MODE_AUTOREGRESSIVE) or\ + (self.attention_kernel == 'autoselected' and length < 128): + return self.apply_attention_dot(query, key, value, decoder_segment_ids, model_mode) + elif self.attention_kernel == 'flash' or\ + self.attention_kernel == 'autoselected': + if model_mode == common_types.MODEL_MODE_AUTOREGRESSIVE: + raise ValueError("""Decode not supported with flash attention. + Use `dot_product` instead.""") + return self.tpu_flash_attention(query, key, value, decoder_segment_ids), None, None + elif self.attention_kernel == 'cudnn_flash_te': + if model_mode == common_types.MODEL_MODE_AUTOREGRESSIVE: + raise ValueError("""Decode not supported with flash attention. + Use `dot_product` instead.""") + return self.cudnn_flash_attention(query, key, value), None, None + else: + raise ValueError(f'Unexpected attention kernel {self.attention_kernel=}.') + + def tpu_flash_attention( + self, + query: Array, + key: Array, + value: Array, + decoder_segment_ids: Array | None) -> Array: + """TPU Flash Attention.""" + # Transpose to ('batch', 'heads', 'length', 'kv') + query = jnp.transpose(query, axes=(0, 2, 1, 3)) + key = jnp.transpose(key, axes=(0, 2, 1, 3)) + value = jnp.transpose(value, axes=(0, 2, 1, 3)) + + + if decoder_segment_ids is not None: + decoder_segment_ids = splash_attention_kernel.SegmentIds( + decoder_segment_ids, decoder_segment_ids + ) + axis_names = nn.logical_to_mesh_axes(self.flash_axis_names) + segment_axis_names = nn.logical_to_mesh_axes( + (BATCH, 'activation_length_no_heads') + ) + + @functools.partial( + shard_map, + mesh=self.mesh, + in_specs=( + axis_names, + axis_names, + axis_names, + segment_axis_names, + ), + out_specs=axis_names, + check_rep=False, + ) + def wrap_flash_attention(query, key, value, decoder_segment_ids): + if decoder_segment_ids is not None: + assert ( + query.shape[2] + == decoder_segment_ids.q.shape[1] + ), 'Sharding along sequence dimension not allowed in tpu kernel attention' + block_sizes = splash_attention_kernel.BlockSizes( + block_q=min(512, query.shape[2]), + block_kv_compute=min(512, key.shape[2]), + block_kv=min(512, key.shape[2]), + block_q_dkv=min(512, query.shape[2]), + block_kv_dkv=min(512, key.shape[2]), + block_kv_dkv_compute=min(512, query.shape[2]), + block_q_dq=min(512, query.shape[2]), + block_kv_dq=min(512, query.shape[2]), + ) + + masks = [splash_attention_mask.CausalMask( shape=(query.shape[2],query.shape[2])) for i in range(query.shape[1])] + multi_head_mask = splash_attention_mask.MultiHeadMask(masks=masks) + splash_kernel = splash_attention_kernel.make_splash_mha(mask = multi_head_mask, + head_shards = 1, + q_seq_shards = 1, + block_sizes = block_sizes) + + return jax.vmap(splash_kernel)(query,key,value, segment_ids = decoder_segment_ids) + + devices_in_data_fsdp = self.mesh.shape['data'] * self.mesh.shape['fsdp'] + assert (query.shape[0] / devices_in_data_fsdp).is_integer(), ( + 'Batch dimension should be shardable among the devices in data and fsdp' + ' axis' + ) + x = wrap_flash_attention(query, key, value, decoder_segment_ids) + x = jnp.transpose(x, axes=(0, 2, 1, 3)) + return x + + def cudnn_flash_attention(self, + query: Array, + key: Array, + value: Array) -> Array: + """CUDNN Flash Attention with Transformer Engine. + + It is an unstable API. In future release, the API can get changed + A stable flash attention API will be included soon. Currently, + 1. It does not support GQA, num_query_heads == num_kv_heads + 2. It supports head_dim till 128 + GQA support with head_dim=256 will be added soon + """ + + # These imports are only meant to work in a GPU build. + import transformer_engine.jax.fused_attn as fused_attn # pytype: disable=import-error + from transformer_engine.jax.fused_attn import AttnBiasType, AttnMaskType, QKVLayout # pytype: disable=import-error + from transformer_engine.jax.fused_attn import is_fused_attn_kernel_available # pytype: disable=import-error + + batch, s_q, n_heads, head_dim = query.shape # pylint: disable=unused-variable + _, s_kv, _, _ = key.shape + + qkv_layout = QKVLayout.BS3HD + attn_mask_type = AttnMaskType.CAUSAL_MASK + attn_bias_type = AttnBiasType.NO_BIAS + + has_fused_attn_kernel = is_fused_attn_kernel_available( + self.dtype, self.dtype, qkv_layout, + attn_bias_type, + attn_mask_type, + self.dropout_rate, self.num_query_heads, + self.num_kv_heads, s_q, + s_kv, head_dim) + + if not has_fused_attn_kernel: + raise ValueError("Flash attention is not supported for current config i.e. head_dim, seq_len, n_heads etc." + "Please see transformer_engine/common/fused_attn/fused_attn.cpp:NVTE_Fused_Attn_Backend for details") + + q = jnp.reshape(query, (*query.shape[:2], 1, *query.shape[-2:])) + k = jnp.reshape(key, (*query.shape[:2], 1, *query.shape[-2:])) + v = jnp.reshape(value, (*query.shape[:2], 1, *query.shape[-2:])) + qkv = jnp.concatenate((q, k, v), axis=2) # to make it (b, s, 3, h, d) + + return fused_attn.self_fused_attn( + qkv=qkv, + bias=None, + mask=jnp.zeros((batch, 1, s_q, s_kv)), # no padding + seed=None, + attn_bias_type=attn_bias_type, + attn_mask_type=attn_mask_type, + scaling_factor=1.0/math.sqrt(head_dim), + dropout_probability=self.dropout_rate, + is_training=True) + + def compute_local_attention(self, + attn_weights: Array, + value: Array) -> tuple[Array, Array, Array]: + """Computes the attention of a local subset of the kv cache. + Local attention results will need to be combined with any other local attentions and normalized + Based on https://github.com/google-research/google-research/blob/master/scaling_transformer_inference_efficiency/attention.py + + Args: + attn_weights (Array): Product of query and key + value (Array): Current value + aqt_rng (PRNGKey | None): Optional rng + + Returns: + (local_out, local_max,): where + local_out is local unnormalized output + local_max is the local max of exponentials + local_sum is the sum of exponentials for this chunk, divided by exp(local_max). + """ + local_max = jnp.max(attn_weights, axis=-1, keepdims=True) + local_exps = jnp.exp(attn_weights - local_max) + local_sum = jnp.sum(local_exps, axis=-1, keepdims=True) + + local_sum = jnp.moveaxis(local_sum, -2, 1) + local_max = jnp.moveaxis(local_max, -2, 1) + + local_max = jnp.reshape(local_max, + (local_max.shape[0], + local_max.shape[1], + local_max.shape[2] * local_max.shape[3], + 1)) + local_sum = jnp.reshape(local_sum, + (local_sum.shape[0], + local_sum.shape[1], + local_sum.shape[2] * local_sum.shape[3], + 1)) + + local_out = self.wv_product(local_exps, value) + return local_out, local_max, local_sum + + def apply_attention_dot( + self, + query: Array, + key: Array, + value: Array, + decoder_segment_ids: Array | None, + model_mode: str = common_types.MODEL_MODE_TRAIN, + ): + """Apply Attention.""" + # Casting qk_product and softmaxt computation for float32 for model stability. + if self.float32_qk_product: + query = query.astype(jnp.float32) + key = key.astype(jnp.float32) + + attn_weights = self.qk_product(query, key) + + # Casting softmaxt computation for float32 for model stability. + if self.float32_logits: + attn_weights = attn_weights.astype(jnp.float32) + attn_mask = self.generate_attention_mask(query, key, decoder_segment_ids, model_mode) + if attn_mask is not None: + attn_weights = apply_mask_to_logits(attn_weights, attn_mask) + return self.compute_local_attention(attn_weights, value) + + def qk_product(self, query: Array, key: Array) -> Array: + """Query-Key product. + + Args: + query: Query projection, in shape of [b, t, n, d], where b: batch size, t: + query length, n: number of heads, d: project dimension. + key: Key projection in shape of [b, s, n_kv, d] for where s: key length, n_kv is + kv heads (sometimes k). The number of group for query is n // n_kv (sometimes g). + + Returns: + results in shape [b, n_kv, n // n_kv, t, s]. + """ + b, t, n, d = query.shape + n_kv = key.shape[-2] + assert n_kv == self.num_kv_heads + query = jnp.reshape(query, (b, t, n_kv, n // n_kv, d)) + result = jnp.einsum('btkgd,bskd->bkgts', query, key) + return result # (4, 8, 1, 1, 6) + + + def wv_product( + self, + attn_weights: Array, + value: Array) -> Array: + """weighted value product. + + Args: + attn_weights: Computed results of qk_einsum, in shape [batch_size, num_kv_heads, group_size, q_len, k_len]. + value: Value projection, in shape of [batch_size, v_len, num_kv_heads, kv_dim]. + + Returns: + result in shape [batch_size, q_len, num_kv_heads * group_size, kv_dim] + """ + out = jnp.einsum('bkgts,bskd->btkgd', attn_weights, value) + b, t, n_kv, g, d = out.shape + result = jnp.reshape(out, (b, t, n_kv * g, d)) + return result + + def revert_kvlen_axis(self, kv): + """Revert key/value length axis. + + Args: + kv: in shape [b, ..., n, d, s]. + + Returns: + reshaped kv as [b, ..., s, n, d] + """ + return jax.numpy.moveaxis(kv, (0,1,2,3), (1,2,0,3)) + + + def move_kvlen_axis(self, kv): + """Move key/value length axis to the end. + + Args: + kv: in shape [b, ..., s, n, d]. + + Returns: + reshaped kv as [b, ..., n, d, s] + """ + return jax.numpy.moveaxis(kv, (0,1,2,3), (2,0,1,3)) + + def cached_kv_shape(self, kv_shape): + """Cached KV shape. + + The key and value have dimension [batch, length, num_heads, head_dim], but + we cache them as [length, num_heads, batch, head_dim, ] for optimized read/write performance. + + Args: + kv_shape: shape of key or value for caching, as [b, ..., s, n, d]. + + Returns: + Swapped kv_shape as [b, ..., n, d, s] for cache. + """ + return (kv_shape[1], kv_shape[2], kv_shape[0], kv_shape[3]) + + def _get_prefill_cache(self, batch, heads, kv_head_size, quantize_kvcache): + dtype = jnp.int8 if quantize_kvcache else jnp.bfloat16 + + kv_cache_layout = ('cache_sequence', 'cache_heads', 'cache_batch', 'cache_kv', ) + cache_logical_shape = (batch, self.max_prefill_predict_length, heads, kv_head_size) + cached_key = self.variable('cache', 'cached_prefill_key', + nn.with_logical_partitioning(jnp.zeros, kv_cache_layout), + self.cached_kv_shape(cache_logical_shape), dtype) + cached_value = self.variable('cache', 'cached_prefill_value', + nn.with_logical_partitioning(jnp.zeros, kv_cache_layout), + self.cached_kv_shape(cache_logical_shape), dtype) + cached_segment_id = self.variable('cache', 'cache_prefill_segment_id', + nn.with_logical_partitioning(jnp.zeros, ('cache_batch', 'cache_sequence')), + (cache_logical_shape[0], self.max_prefill_predict_length), jnp.int32) + + if self.quantize_kvcache: + cache_logical_shape_scale = (batch, self.max_prefill_predict_length, heads, 1) + cached_key_scale_var = self.variable('cache', 'cached_prefill_key_scale', + nn.with_logical_partitioning(jnp.zeros, kv_cache_layout), + self.cached_kv_shape(cache_logical_shape_scale), jnp.bfloat16) + cached_value_scale_var = self.variable('cache', 'cached_prefill_value_scale', + nn.with_logical_partitioning(jnp.zeros, kv_cache_layout), + self.cached_kv_shape(cache_logical_shape_scale), jnp.bfloat16) + else: + cached_key_scale_var = None + cached_value_scale_var = None + + key_vars = (cached_key, cached_key_scale_var) + value_vars = (cached_value, cached_value_scale_var) + return key_vars, value_vars, cached_segment_id + + def _get_ar_cache(self, batch, heads, kv_head_size, quantize_kvcache): + dtype = jnp.int8 if quantize_kvcache else jnp.bfloat16 + cache_length = self.max_target_length - self.max_prefill_predict_length + kv_cache_layout = ('cache_sequence', 'cache_heads', 'cache_batch', 'cache_kv', ) + cache_logical_shape = (batch, cache_length, heads, kv_head_size) + cached_key = self.variable('cache', 'cached_ar_key', + nn.with_logical_partitioning(jnp.zeros, kv_cache_layout), + self.cached_kv_shape(cache_logical_shape), dtype) + cached_value = self.variable('cache', 'cached_ar_value', + nn.with_logical_partitioning(jnp.zeros, kv_cache_layout), + self.cached_kv_shape(cache_logical_shape), dtype) + cached_segment_id = self.variable('cache', 'cache_ar_segment_id', + nn.with_logical_partitioning(jnp.zeros, ('cache_batch', 'cache_sequence')), + (cache_logical_shape[0], cache_length), jnp.int32) + + if self.quantize_kvcache: + cache_logical_shape_scale = (batch, cache_length, heads, 1) + cached_key_scale_var = self.variable('cache', 'cached_ar_key_scale', + nn.with_logical_partitioning(jnp.zeros, kv_cache_layout), + self.cached_kv_shape(cache_logical_shape_scale), jnp.bfloat16) + cached_value_scale_var = self.variable('cache', 'cached_ar_value_scale', + nn.with_logical_partitioning(jnp.zeros, kv_cache_layout), + self.cached_kv_shape(cache_logical_shape_scale), jnp.bfloat16) + else: + cached_key_scale_var = None + cached_value_scale_var = None + + cache_index = self.variable('cache', 'cache_ar_index', + nn.with_logical_partitioning(jnp.zeros, ()), + (1,), jnp.int32) + key_vars = (cached_key, cached_key_scale_var) + value_vars = (cached_value, cached_value_scale_var) + return key_vars, value_vars, cached_segment_id, cache_index + + def kv_cache_prefill(self, + key: Array, + value: Array, + decoder_segment_ids: Array, + ): + """In prefill mode, we zero out the existing cache, run the computation and + prepare the cache as necessary. + + Args: + key: in shape [b, s, n, d]. + value: in shape [b, s, n, d]. + decoder_segment_ids: [b, s] -- marking segment ids for tokens + + Returns: + key, value, decoder_segment_id. + + """ + batch, sequence, heads, kv_head_size = key.shape + assert key.dtype == value.dtype, "Key and Value Dtypes should match." + + cached_prefill_key_var, cached_prefill_value_var, cached_prefill_segment_id = self._get_prefill_cache(batch, heads, kv_head_size, self.quantize_kvcache) + self._get_ar_cache(batch, heads, kv_head_size, self.quantize_kvcache) # initialize it now + + key_shaped_for_cache = self.move_kvlen_axis(key) + value_shaped_for_cache = self.move_kvlen_axis(value) + + if self.quantize_kvcache: + key_shaped_for_cache, key_scale = quantizations.quantize_kv(key_shaped_for_cache) + value_shaped_for_cache, value_scale = quantizations.quantize_kv(value_shaped_for_cache) + cached_prefill_key_var[1].value = key_scale + cached_prefill_value_var[1].value = value_scale + + cached_prefill_key_var[0].value = key_shaped_for_cache + cached_prefill_value_var[0].value = value_shaped_for_cache + + if decoder_segment_ids is not None: + cached_prefill_segment_id.value = decoder_segment_ids + + return key, value, decoder_segment_ids + + + def update_ar_key_value(self, + one_token_key: Array, + one_token_value: Array, + cached_key_vars: tuple[nn.Variable, nn.Variable|None], + cached_value_vars: tuple[nn.Variable, nn.Variable|None], + one_hot_indices: Array) -> tuple[Array, Array]: + """Adds a single token's results to the ar kv cache + + Args: + one_token_key (Array): Key of one token to add to the cache + one_token_value (Array): Value of one token to add to the cache + cached_ar_key (tuple[nn.Variable, nn.Variable|None],): Cached keys to add new token key to, possibly with scale + cached_ar_value (tuple[nn.Variable, nn.Variable|None],: Cached values to add new token value to, possible with scale + one_hot_indices (Array): Location of the new token within the cache + + Returns: + tuple[Array, Array]: Updated caches for key and value with new token info added + """ + + cached_key_var, cached_key_scale_var = cached_key_vars + cached_value_var, cached_value_scale_var = cached_value_vars + + # In order to update the key, value caches with the current key and + # value, we move the length axis to the back + one_token_key = self.move_kvlen_axis(one_token_key) + one_token_value = self.move_kvlen_axis(one_token_value) + + if self.quantize_kvcache: + one_token_key, one_token_key_scale = quantizations.quantize_kv(one_token_key) + one_token_value, one_token_value_scale = quantizations.quantize_kv(one_token_value) + + one_hot_indices = one_hot_indices.astype(int) + + + ar_key = cached_key_var.value + ar_key = jax.lax.dynamic_update_index_in_dim(ar_key, one_token_key, jnp.squeeze(one_hot_indices), 0) + ar_key = nn.with_logical_constraint(ar_key, ('cache_sequence', 'cache_heads', 'cache_batch', 'cache_kv',)) + cached_key_var.value = ar_key + + ar_value = cached_value_var.value + ar_value = jax.lax.dynamic_update_index_in_dim(ar_value, one_token_value, jnp.squeeze(one_hot_indices), 0) + ar_value = nn.with_logical_constraint(ar_value, ('cache_sequence', 'cache_heads', 'cache_batch', 'cache_kv',)) + cached_value_var.value = ar_value + + if self.quantize_kvcache: + ar_key_scale = jax.lax.dynamic_update_index_in_dim(cached_key_scale_var.value, one_token_key_scale, jnp.squeeze(one_hot_indices), 0) + ar_value_scale = jax.lax.dynamic_update_index_in_dim(cached_value_scale_var.value, one_token_value_scale, jnp.squeeze(one_hot_indices), 0) + cached_key_scale_var.value = ar_key_scale + cached_value_scale_var.value = ar_value_scale + + ar_key = quantizations.unquantize_kv(cached_key_var.value, cached_key_scale_var.value, one_token_key.dtype) + ar_value = quantizations.unquantize_kv(cached_value_var.value, cached_value_scale_var.value, one_token_value.dtype) + + # Move the keys and values back to their original shapes. + return self.revert_kvlen_axis(ar_key), self.revert_kvlen_axis(ar_value) + + def prefill_cache_var_model_var(self, cache_var, target_dtype): + if not self.quantize_kvcache: + return self.revert_kvlen_axis(cache_var[0].value) + else: + raw_cache, quant_scale = cache_var + raw_cache_unquantized = quantizations.unquantize_kv(raw_cache.value, quant_scale.value, target_dtype) + return self.revert_kvlen_axis(raw_cache_unquantized) + + + + def kv_cache_autoregressive(self, + key: Array, + value: Array, + ): + """In autoregressive mode, we update the cache for this entry and + then return the full cache. + + Args: + key: in shape [b, 1, n, d]. + value: in shape [b, 1, n, d]. + decoder_segment_ids: [b, 1] -- marking segment ids for tokens + + Returns: + tuple of (key, value, segment_id) for both prefill and ar cache, + Raises: + ValueError: when key/value shape is not [batch, 1, num_heads, heads_dim]. + """ + batch, sequence, heads, kv_head_size = key.shape + if sequence != 1: + raise ValueError(f"Sequence length should be 1 during autoregression, got {sequence=}") + is_initialized = self.has_variable('cache', 'cache_ar_index') + if not is_initialized: + raise ValueError("Error, we can't do autoregression if we haven't seeded the KV Cache.") + + cached_ar_key_var, cached_ar_value_var, cached_ar_segment_id, cache_ar_index = self._get_ar_cache(batch, heads, kv_head_size, self.quantize_kvcache) + + key = nn.with_logical_constraint(key, (BATCH, LENGTH, HEAD, D_KV)) + value = nn.with_logical_constraint(value, (BATCH, LENGTH, HEAD, D_KV)) + + ar_key, ar_value = self.update_ar_key_value(key, value, cached_ar_key_var, cached_ar_value_var, cache_ar_index.value) + active_indicator = jnp.zeros((batch, 1), dtype = jnp.int32) + common_types.DECODING_ACTIVE_SEQUENCE_INDICATOR + cached_ar_segment_id.value = jax.lax.dynamic_update_index_in_dim(cached_ar_segment_id.value, active_indicator, jnp.squeeze(cache_ar_index.value), 1) + cache_ar_index.value = jnp.mod(cache_ar_index.value + 1, self.max_target_length - self.max_prefill_predict_length) + + # Prep and return both prefill and ar caches + cached_prefill_key_var, cached_prefill_value_var, cached_prefill_segment_id = self._get_prefill_cache(self.max_target_length, heads, kv_head_size, self.quantize_kvcache) + + cached_prefill = self.prefill_cache_var_model_var(cached_prefill_key_var, key.dtype), self.prefill_cache_var_model_var(cached_prefill_value_var, value.dtype), cached_prefill_segment_id.value + return cached_prefill, (ar_key, ar_value, cached_ar_segment_id.value) + + def kv_cache( + self, + key: Array, + value: Array, + decoder_segment_ids: Array, + model_mode: str + ) -> tuple: + """KV cache takes the current state and updates the state accordingly. + + The key and value have dimension [batch, length, num_heads, head_dim], + but we cache them as [batch, num_heads, head_dim, length] as a TPU + fusion optimization. This also enables the "scatter via one-hot + broadcast" trick, which means we do a one-hot broadcast instead of a + scatter/gather operations, resulting in a 3-4x speedup in practice. + + Args: + key: in shape [b, s, n, d]. + value: in shape [b, s, n, d]. + model_mode: model mode controlling model + + Returns: + two tuples of (k, v, decoder_segments) -- either can be Nones + + """ + if key.shape != value.shape: + raise ValueError(f"Can't KV cache with mismatched shapes {key.shape=}, {value.shape=}") + + + if model_mode == common_types.MODEL_MODE_TRAIN: + return (key, value, decoder_segment_ids), None + elif model_mode == common_types.MODEL_MODE_PREFILL: + return self.kv_cache_prefill(key, value, decoder_segment_ids), None + elif model_mode == common_types.MODEL_MODE_AUTOREGRESSIVE: + return self.kv_cache_autoregressive(key, value) + else: + raise ValueError(f"Model Mode isn't supported! {model_mode=}") + + + def normalize_attention(self, + local_outs, + local_maxes, + local_sums): + """Normalize across multiple localized attentions + + Args: + local_outs (list): List of unnormalized outputs entries for each local attention + local_maxes (list): List of max exponentials entries for each local attention + local_sums (list): List of exponential sum entries for each local attention + + Returns: + Array: Combined attention that has been normalized + """ + # Based on https://github.com/google-research/google-research/blob/master/scaling_transformer_inference_efficiency/attention.py + global_max = functools.reduce(jnp.maximum, local_maxes) + global_sum = sum([ + jnp.exp(local_max - global_max) * local_sum + for (local_sum, local_max) in zip(local_sums, local_maxes) + ]) + + attn_out = 0 + for local_max, local_out in zip(local_maxes, local_outs): + local_normalizer = jnp.exp(local_max - global_max) / global_sum + attn_out += local_normalizer * local_out + return attn_out + + + @nn.compact + def __call__(self, query, key, value, decoder_segment_ids, model_mode): + prefill_kv_cache, ar_kv_cache = self.kv_cache(key, value, decoder_segment_ids, model_mode) + + prefill_unnormalized_output, prefill_exponentials_max, prefill_exponentials_sum = self.apply_attention( + query=query, + key=prefill_kv_cache[0], + value=prefill_kv_cache[1], + decoder_segment_ids=prefill_kv_cache[2], + model_mode=model_mode, + ) + + # Return the "prefill" cache if it actually the combined prefill+ar kv cache + if ar_kv_cache is None: + if prefill_exponentials_sum is not None: + return prefill_unnormalized_output / prefill_exponentials_sum + return prefill_unnormalized_output + + ar_unnormalized_output, ar_exponentials_max, ar_exponentials_sum = self.apply_attention( + query=query, + key=ar_kv_cache[0], + value=ar_kv_cache[1], + decoder_segment_ids=ar_kv_cache[2], + model_mode=model_mode, + ) + + unnormalized_outputs = [prefill_unnormalized_output, ar_unnormalized_output] + exponentials_maxes = [prefill_exponentials_max, ar_exponentials_max] + exponentials_sums = [prefill_exponentials_sum, ar_exponentials_sum] + return self.normalize_attention(unnormalized_outputs, exponentials_maxes, exponentials_sums) + + +class Attention(nn.Module): + """ Generic Attention. + + Attributes: + num_query_heads: number of query attention heads. Features (i.e. inputs_q.shape[-1]) + should be divisible by the number of heads. + num_kv_heads: number of kv attention heads. + head_dim: dimension of each head. + mesh: Mesh, device mesh + attention_kernel: str, guidance on if we should use an attention kernel + dtype: the dtype of the computation. + weight_dtype: the dtype of the weights. + max_target_length: maximum target length + max_prefill_predict_length: size of the maximum prefill + dropout_rate: dropout rate + kernel_init: initializer for the kernel of the Dense layers. + float32_qk_product: bool, if True then compute logits via float32 qk_product to avoid + numerical issues with bfloat16. + float32_logits: bool, if True then cast logits to float32 before softmax to avoid + numerical issues with bfloat16. + quant: Quant, stores quantization parameters, defaults to None implying no quantization. + quantize_kvcache: bool, quantize the kv cache. + """ + + config: Config + num_query_heads: int + num_kv_heads: int + head_dim: int + max_target_length: int + mesh: Mesh + attention_kernel: str + dtype: DType = jnp.float32 + weight_dtype: DType = jnp.float32 + max_prefill_predict_length: int = -1 + dropout_rate: float = 0. + kernel_init: NdInitializer = nd_dense_init(1.0, 'fan_in', 'normal') + float32_qk_product: bool = False # computes logits in float32 for stability. + float32_logits: bool = False # cast logits in float32 for stability. + quant: Optional[Quant] = None + quantize_kvcache: bool = False + + + query_axis_names: AxisNames = (BATCH, LENGTH, HEAD, D_KV) + key_axis_names: AxisNames = (BATCH, LENGTH, HEAD, D_KV) + value_axis_names: AxisNames = (BATCH, LENGTH, HEAD, D_KV) + out_axis_names: AxisNames = (BATCH, LENGTH, HEAD, D_KV) + + def query_projection(self, inputs_q: Array) -> Array: + """Query projection.""" + + # NOTE: T5 does not explicitly rescale the attention logits by + # 1/sqrt(depth_kq)! This is folded into the initializers of the + # linear transformations, which is equivalent under Adafactor. + depth_scaling = jnp.sqrt(self.head_dim).astype(self.dtype) + def query_init(*args): + #pylint: disable=no-value-for-parameter + return self.kernel_init(*args) / depth_scaling + + query_proj = DenseGeneral( + features=(self.num_query_heads, self.head_dim), + axis=-1, + kernel_init=query_init, + kernel_axes=('embed', 'heads', 'kv'), + dtype=self.dtype, + weight_dtype=self.weight_dtype, + name='query', + quant=self.quant)(inputs_q) + return query_proj + + def kv_projection(self, inputs_kv: Array, proj_name: str) -> Array: + """Projection for Key and Value. + + Args: + inputs_kv: inputs_kv: key/values of shape `[batch, kv_length, + num_kv_heads, kv_dim]`. + proj_name: name of projection, `key` or `value`. + + Returns: + Projection of key or value, in shape of `[batch, kv_length, head_dim]`. + """ + if self.num_kv_heads == -1: + raise ValueError('num_kv_heads is not defined.') + + if self.num_query_heads % self.num_kv_heads != 0: + raise ValueError('Invaid num_kv_heads for GQA.') + + kv_proj = DenseGeneral( + features=(self.num_kv_heads, self.head_dim), + axis=-1, + kernel_init=self.kernel_init, + kernel_axes=('embed', 'heads', 'kv'), + dtype=self.dtype, + weight_dtype=self.weight_dtype, + name=proj_name, + quant=self.quant)(inputs_kv) + return kv_proj + + def qkv_projection(self, inputs: Array, proj_name: str): + """ Fused QKV projection""" + + qkv_proj = DenseGeneral( + features=(3, self.num_query_heads, self.head_dim), + axis = -1, + kernel_init=self.kernel_init, + kernel_axes=('embed', 'qkv', 'heads', 'kv'), + dtype=self.dtype, + weight_dtype=self.weight_dtype, + name=proj_name, + quant=self.quant)(inputs) + qkv_proj = checkpoint_name(qkv_proj, 'qkv_proj') + query, key, value = qkv_proj[:,:,0,...], qkv_proj[:,:,1,...], qkv_proj[:,:,2,...] + return query, key, value + + def out_projection(self, output_dim: int, out: Array) -> Array: + out_proj = DenseGeneral( + features=output_dim, + axis=(-2, -1), + kernel_init=self.kernel_init, + kernel_axes=('heads', 'kv', 'embed'), + dtype=self.dtype, + weight_dtype=self.weight_dtype, + name='out', + quant=self.quant)(out) + return out_proj + + def key_rotary(self, key: Array, inputs_positions: Array): + """Apply Rotary Embedding to key.""" + key = RotaryEmbedding( + embedding_dims=self.head_dim, + name='key_rotary')(inputs=key, position=inputs_positions) + return key + + @nn.compact + def __call__(self, + inputs_q: Array, + inputs_kv: Array, + inputs_positions: Array, + decoder_segment_ids: Array | None = None, + *, + model_mode: str = common_types.MODEL_MODE_TRAIN, + deterministic: bool = False): + """Applies Attention on the input data. + + Projects the inputs into multi-headed query, key, and value vectors, + applies dot-product attention and project the results to an output vector. + + There are three modes: training, prefill and autoregression. During training, the KV cahce + is ignored. During prefill, the cache is filled. During autoregression the cache is used. + + In the cache initialization call, `inputs_q` has a shape [batch, length, + q_features] and `inputs_kv`: [batch, length, kv_features]. During the + incremental decoding stage, query, key and value all have the shape [batch, + 1, qkv_features] corresponding to a single step. + + Args: + inputs_q: input queries of shape `[batch, q_length, q_features]`. + inputs_kv: key/values of shape `[batch, kv_length, kv_features]`. + model_mode: corresponding to train, prefill and decode. + deterministic: Disables dropout if set to True. + + Returns: + output of shape `[batch, length, q_features]`. + """ + # apply projection. + if self.config.fused_qkv: + query, key, value = self.qkv_projection(inputs_q, proj_name='qkv_proj') + else: + query = self.query_projection(inputs_q) + key = self.kv_projection(inputs_kv, proj_name='key') + value = self.kv_projection(inputs_kv, proj_name='value') + + # apply ROPE + query = RotaryEmbedding( + embedding_dims=self.head_dim, name='query_rotary' + )(inputs=query, position=inputs_positions) + key = self.key_rotary(key, inputs_positions) + + # annotate with sharding constraint. + query = nn.with_logical_constraint(query, self.query_axis_names) + query = checkpoint_name(query, 'query_proj') + key = nn.with_logical_constraint(key, self.key_axis_names) + key = checkpoint_name(key, 'key_proj') + value = nn.with_logical_constraint(value, self.value_axis_names) + value = checkpoint_name(value, 'value_proj') + + attention_op = AttentionOp(mesh=self.mesh, + attention_kernel=self.attention_kernel, + max_target_length=self.max_target_length, + max_prefill_predict_length=self.max_prefill_predict_length, + float32_qk_product=self.float32_qk_product, + float32_logits=self.float32_logits, + quant=self.quant, + quantize_kvcache=self.quantize_kvcache, + num_query_heads=self.num_query_heads, + num_kv_heads=self.num_kv_heads, + dropout_rate = self.dropout_rate, + dtype=self.dtype) + + out = attention_op(query, key, value, decoder_segment_ids, model_mode) + + out = nn.with_logical_constraint(out, self.out_axis_names) + + # apply output projection, output dim is set to the input dim. + out = self.out_projection(inputs_q.shape[-1], out) + out = checkpoint_name(out, 'out_proj') + return out diff --git a/maxtext-setup/maxtext/MaxText/layers/embeddings.py b/maxtext-setup/maxtext/MaxText/layers/embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..ac773ab710f9ceae80540ffee81ee635fd990a2e --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/embeddings.py @@ -0,0 +1,201 @@ +# Copyright 2023 Google LLC +# +# 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. + +"""Embedding Layers.""" + +from typing import Any, Optional + +from flax import linen as nn +import jax +from jax import lax +import jax.numpy as jnp +from layers import initializers + +Config = Any +Array = jnp.ndarray +DType = jnp.dtype + +Initializer = initializers.Initializer +default_embed_init = initializers.default_embed_init +with_logical_partitioning = nn.with_logical_partitioning + +_MAX_WAVELENGTH = 10_000 + +class Embed(nn.Module): + """A parameterized function from integers [0, n) to d-dimensional vectors. + + Attributes: + num_embeddings: number of embeddings. + features: number of feature dimensions for each embedding. + dtype: the dtype of the embedding vectors (default: float32). + embedding_init: embedding initializer. + """ + + # pylint: disable=attribute-defined-outside-init + config: Config + num_embeddings: int + features: int + cast_input_dtype: Optional[DType] = None + dtype: DType = jnp.float32 + attend_dtype: Optional[DType] = None + embedding_init: Initializer = default_embed_init + + def setup(self): + self.embedding = self.param( + 'embedding', + with_logical_partitioning(self.embedding_init, ('vocab', 'embed')), + (self.num_embeddings, self.features), + self.config.weight_dtype, + ) + + def __call__(self, inputs: Array) -> Array: + """Embeds the inputs along the last dimension. + + Args: + inputs: input data, all dimensions are considered batch dimensions. + + Returns: + Output which is embedded input data. The output shape follows the input, + with an additional `features` dimension appended. + """ + cfg = self.config + if self.cast_input_dtype: + inputs = inputs.astype(self.cast_input_dtype) + if not jnp.issubdtype(inputs.dtype, jnp.integer): + raise ValueError('Input type must be an integer or unsigned integer.') + + if cfg.use_iota_embed: + iota = lax.iota(jnp.int32, self.num_embeddings) + one_hot = jnp.array(inputs[..., jnp.newaxis] == iota, dtype=self.dtype) + output = jnp.dot(one_hot, jnp.asarray(self.embedding, self.dtype)) + else: + output = jnp.asarray(self.embedding, self.dtype)[inputs] + output = nn.with_logical_constraint( + output, ('activation_batch', 'activation_length', 'activation_embed') + ) + return output + + def attend(self, query: Array) -> Array: + """Attend over the embedding using a query array. + + Args: + query: array with last dimension equal the feature depth `features` of the + embedding. + + Returns: + An array with final dim `num_embeddings` corresponding to the batched + inner-product of the array of query vectors against each embedding. + Commonly used for weight-sharing between embeddings and logit transform + in NLP models. + """ + dtype = self.attend_dtype if self.attend_dtype is not None else self.dtype + return jnp.dot(query, jnp.asarray(self.embedding, jnp.bfloat16).T) + + +class RotaryEmbedding(nn.Module): + """RoPE + + Attributes: + min_timescale: Start of the geometric index. Determines the periodicity of + the added signal. + max_timescale: End of the geometric index. Determines the frequency of the + added signal. + embedding_dims: Dimension of the embedding to be generated. + """ + + min_timescale: int = 1 + max_timescale: int = 10_000 + embedding_dims: int = 0 + cast_as_fprop_dtype: bool = True + fprop_dtype: DType = jnp.bfloat16 + + def setup(self) -> None: + if self.embedding_dims % 2: + raise ValueError( + 'Embedding dim for rotary position embedding must be a multiple of 2.' + ) + + def __call__( + self, # pytype: disable=signature-mismatch # overriding-parameter-count-checks + inputs: jax.Array, + position: jax.Array, + ) -> jax.Array: + """Generates a jax.Array of sinusoids with different frequencies. + + Args: + inputs: The input sequence on which to apply the Rotary position + embedding. Since rotary position embeddings are applied to query and + keys after projection, it is assumed of shape [B, S, N, H]. + position: Optional position jax.Array which denotes the position of each + token in the sequence. This only needs to be supplied when the sequence + is packed. It is of shape [B, S]. + + Returns: + a jax.Array of shape [B, S, N, H] which includes the inputs together with + the rotary position embedding incorporated in it. + """ + assert position is not None + if len(inputs.shape) != 4: + raise ValueError( + 'Input is assumed to be a rank 4 tensor of shape' + '[batch, sequence, heads, dims].' + ) + if self.embedding_dims != inputs.shape[3]: + raise ValueError( + 'The embedding dims of the rotary position embedding' + 'must match the hidden dimension of the inputs.' + ) + half_embedding_dim = self.embedding_dims // 2 + fraction = 2 * jnp.arange(0, half_embedding_dim) / self.embedding_dims + timescale = ( + self.min_timescale + * (self.max_timescale / self.min_timescale) ** fraction + ) + position = position[:, :, jnp.newaxis, jnp.newaxis] + sinusoid_inp = position / timescale + sin = jnp.sin(sinusoid_inp) + cos = jnp.cos(sinusoid_inp) + first_half, second_half = jnp.split(inputs, 2, axis=-1) + first_part = first_half * cos - second_half * sin + second_part = second_half * cos + first_half * sin + if self.cast_as_fprop_dtype: + first_part = first_part.astype(self.fprop_dtype) + second_part = second_part.astype(self.fprop_dtype) + x_out = jnp.concatenate((first_part, second_part), axis=-1) + return x_out + + +class PositionalEmbedding(nn.Module): + embedding_dims: int + max_wavelength: int = _MAX_WAVELENGTH + + def __call__( + self, # pytype: disable=signature-mismatch # overriding-parameter-count-checks + input_embedding: jax.Array, + position: jax.Array, + ) -> jax.Array: + num_timescales = self.embedding_dims // 2 + log_timescale_increment = jnp.log(float(self.max_wavelength)) / jnp.maximum( + jnp.asarray(num_timescales, dtype=jnp.float32) - 1, 1 + ) + inv_timescales = jnp.exp( + jnp.arange(num_timescales, dtype=jnp.float32) * -log_timescale_increment + ) + position = position[:, :, jnp.newaxis] + inv_timescales = inv_timescales[jnp.newaxis, jnp.newaxis, :] + scaled_time = position * inv_timescales + signal = jnp.concatenate([jnp.sin(scaled_time), jnp.cos(scaled_time)], axis = -1) + # signal = jnp.pad(signal, [[0, jnp.mod(self.embedding_dims, 2)]]) + position_embedding = signal.astype(jnp.float32) + return input_embedding + position_embedding \ No newline at end of file diff --git a/maxtext-setup/maxtext/MaxText/layers/gemma.py b/maxtext-setup/maxtext/MaxText/layers/gemma.py new file mode 100644 index 0000000000000000000000000000000000000000..cbbadf7bc04a0eb30a65547696364928c7b13056 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/gemma.py @@ -0,0 +1,158 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +from flax import linen as nn +import common_types +import jax.numpy as jnp + +from layers import normalizations +from layers import attentions +from layers import initializers +from layers import embeddings +from layers import linears +from layers import quantizations + +from typing import Optional + +Embed = embeddings.Embed +RMSNorm = normalizations.RMSNorm +NdInitializer = initializers.NdInitializer +Attention = attentions.Attention +MlpBlock = linears.MlpBlock +Config = common_types.Config +AxisNames = common_types.AxisNames +Mesh = common_types.Mesh +ScanIn = common_types.ScanIn +DType = common_types.DType +Array = common_types.Array +BATCH = common_types.BATCH +LENGTH = common_types.LENGTH +HEAD = common_types.HEAD +D_KV = common_types.D_KV +DEFAULT_MASK_VALUE = -0.7 * float(jnp.finfo(jnp.dtype("float32")).max) + + +nd_dense_init = initializers.nd_dense_init +Quant = quantizations.AqtQuantization + + +# Decoder and Model definitions +class GemmaDecoderLayer(nn.Module): + """Transformer decoder layer that attends to the encoder.""" + config: Config + mesh: Mesh + quant: Optional[Quant] = None + + @nn.compact + def __call__(self, + inputs, + decoder_segment_ids, + decoder_positions, + deterministic, + model_mode, + ): + cfg = self.config + mesh = self.mesh + inputs = nn.with_logical_constraint( + inputs, ('activation_batch', 'activation_length', 'activation_embed')) + + # inputs: embedded inputs to the decoder with shape [batch, length, emb_dim] + lnx = RMSNorm( + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='pre_self_attention_norm', + kernel_axes=('embed',))(inputs) + + lnx = nn.with_logical_constraint( + lnx, ('activation_batch', 'activation_length', 'activation_embed')) + + attention_layer = Attention( + config=cfg, + num_query_heads=cfg.num_query_heads, + num_kv_heads=cfg.num_kv_heads, + head_dim=cfg.head_dim, + max_target_length=cfg.max_target_length, + max_prefill_predict_length=cfg.max_prefill_predict_length, + attention_kernel=cfg.attention, + mesh=mesh, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + dropout_rate=cfg.dropout_rate, + name='self_attention', + float32_qk_product = True, + float32_logits = True, + quant=self.quant, + quantize_kvcache=cfg.quantize_kvcache) + + attention_lnx = attention_layer( + lnx, + lnx, + decoder_positions, + decoder_segment_ids=decoder_segment_ids, + deterministic=deterministic, + model_mode=model_mode) + + attention_lnx = nn.with_logical_constraint( + attention_lnx, + ('activation_batch', 'activation_length', 'activation_embed')) + attention_lnx += inputs + residual = attention_lnx + attn_output = RMSNorm( + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='pre_ffw_norm', + kernel_axes=('embed',))(attention_lnx) + + # MLP block. + mlp_lnx = MlpBlock( + intermediate_dim=cfg.mlp_dim, + activations=cfg.mlp_activations, + intermediate_dropout_rate=cfg.dropout_rate, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='mlp', + config=cfg, + quant=self.quant, + )(attn_output, deterministic=deterministic) + mlp_lnx = nn.with_logical_constraint( + mlp_lnx, ('activation_batch', 'activation_length', 'activation_embed') + ) + + next_layer_addition = mlp_lnx + residual + + next_layer_addition_dropped_out = nn.Dropout( + rate=cfg.dropout_rate, broadcast_dims=(-2,) + )(next_layer_addition, deterministic=deterministic) + + layer_output = next_layer_addition_dropped_out + layer_output = nn.with_logical_constraint( + layer_output, + ('activation_batch', 'activation_length', 'activation_embed'), + ) + + if cfg.record_internal_nn_metrics: + self.sow('intermediates', 'activation_mean', jnp.mean(layer_output)) + self.sow('intermediates', 'activation_stdev', jnp.std(layer_output)) + self.sow( + 'intermediates', + 'activation_fraction_zero', + jnp.sum(layer_output == 0) / jnp.size(layer_output), + ) + + if cfg.scan_layers: + return layer_output, None + else: + return layer_output diff --git a/maxtext-setup/maxtext/MaxText/layers/gpt3.py b/maxtext-setup/maxtext/MaxText/layers/gpt3.py new file mode 100644 index 0000000000000000000000000000000000000000..518ec29124ea6f8b2b365240e97559547b9c2f7f --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/gpt3.py @@ -0,0 +1,356 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Transformer model definition.""" +# pylint: disable=arguments-differ +# pylint: disable=no-name-in-module + + +from typing import Any, Optional, Tuple + +from jax.sharding import Mesh +from jax import lax +import jax.numpy as jnp +from jax.ad_checkpoint import checkpoint_name + +from flax import linen as nn + +from layers import attentions +from layers import initializers +from layers import linears +from layers import models +from layers import quantizations + +AttentionOp = attentions.AttentionOp + +import common_types + +Array = common_types.Array +Config = common_types.Config +DType = common_types.DType +Mesh = common_types.Mesh +AxisNames = common_types.AxisNames +BATCH = common_types.BATCH +LENGTH = common_types.LENGTH +HEAD = common_types.HEAD +D_KV = common_types.D_KV + +DenseGeneral = linears.DenseGeneral +NdInitializer = initializers.NdInitializer +Initializer = initializers.Initializer +nd_dense_init = initializers.nd_dense_init +Quant = quantizations.AqtQuantization + + +#----------------------------------------- +# The Normalization Layer specific for GPT3 +#----------------------------------------- + +class Gpt3LayerNorm(nn.Module): + """GPT3 Layer normalization operating on the last axis of the input data.""" + epsilon: float = 1e-6 + dtype: Any = jnp.float32 + weight_dtype: Any = jnp.float32 + kernel_axes: Tuple[str, ...] = () + scale_init: Initializer = nn.initializers.zeros + use_bias: bool = True + reductions_in_fp32: bool = False + + @nn.compact + def __call__(self, x: jnp.ndarray) -> jnp.ndarray: + """Applies layer normalization on the input.""" + if self.reductions_in_fp32: + x = jnp.asarray(x, jnp.float32) + mean = jnp.mean(x, axis=[-1], keepdims=True) + var = jnp.mean(jnp.square(x - mean), axis=[-1], keepdims=True) + normed_inputs = (x - mean) * lax.rsqrt(var + self.epsilon) + if self.reductions_in_fp32: + normed_inputs = normed_inputs.astype(self.dtype) + + features = x.shape[-1] + scale = self.param( + 'scale', + nn.with_logical_partitioning(self.scale_init, self.kernel_axes), + (features,), + self.weight_dtype + ) + + scale = jnp.asarray(scale, self.dtype) + output = normed_inputs * (scale + 1) + + if self.use_bias: + bias = self.param( + 'bias', + nn.with_logical_partitioning(initializers.default_bias_init, self.kernel_axes), + (features,), + self.weight_dtype, + ) + bias = jnp.asarray(bias, self.dtype) + output += bias + return output + + +#----------------------------------------- +# The Attention Layer specific for GPT3 +#----------------------------------------- + +class Gpt3MultiHeadAttention(nn.Module): + """Multi-head attention in gpt3. + + Attributes: + num_heads: number of attention heads. Features (i.e. inputs_q.shape[-1]) + should be divisible by the number of heads. + head_dim: dimension of each head. + max_target_length: maximum length of output + max_prefill_predict_length: size of the maximum prefill + mesh: device mesh + dtype: the dtype of the computation. + dropout_rate: dropout rate + kernel_init: initializer for the kernel of the Dense layers. + float32_qk_product: bool, if True then compute logits via float32 qk_product to avoid + numerical issues with bfloat16. + float32_logits: bool, if True then cast logits to float32 before softmax to avoid + numerical issues with bfloat16. + fused_qkv: whether to fuse query, key and value into one projection. + quant: Quant, stores quantization config, defaults to None implying no quantization. + use_bias: whether to add bias in linear transformation. + """ + + config: Config + num_heads: int + head_dim: int + max_target_length: int + max_prefill_predict_length: int + mesh: Mesh + attention_kernel: str + dtype: DType = jnp.float32 + weight_dtype: DType = jnp.float32 + dropout_rate: float = 0. + kernel_init: NdInitializer = nd_dense_init(1.0, 'fan_in', 'normal') + float32_qk_product: bool = False # computes logits in float32 for stability. + float32_logits: bool = True # cast logits in float32 for stability. + fused_qkv: bool = True + quant: Optional[Quant] = None + use_bias: bool = True + + query_axis_names: AxisNames = (BATCH, LENGTH, HEAD, D_KV) + key_axis_names: AxisNames = (BATCH, LENGTH, HEAD, D_KV) + value_axis_names: AxisNames = (BATCH, LENGTH, HEAD, D_KV) + out_axis_names: AxisNames = (BATCH, LENGTH, HEAD, D_KV) + + def qkv_projection(self, inputs: Array, proj_name: str): + """ Fused QKV projection""" + + qkv_proj = DenseGeneral( + features=(3, self.num_heads, self.head_dim), + axis = -1, + kernel_init=self.kernel_init, + kernel_axes=('embed', 'qkv', 'heads', 'kv'), + dtype=self.dtype, + weight_dtype=self.weight_dtype, + name=proj_name, + quant=self.quant, + use_bias=self.use_bias, + )(inputs) + qkv_proj = checkpoint_name(qkv_proj, 'qkv_proj') + query, key, value = qkv_proj[:,:,0,...], qkv_proj[:,:,1,...], qkv_proj[:,:,2,...] + return query, key, value + + def projection(self, inputs: Array, proj_name: str) -> Array: + """individual projection for one of q, k and v.""" + proj = DenseGeneral( + features=(self.num_heads, self.head_dim), + axis=-1, + kernel_init=self.kernel_init, + kernel_axes=('embed', 'heads', 'kv'), + dtype=self.dtype, + weight_dtype=self.weight_dtype, + name=proj_name, + quant=self.quant, + use_bias=self.use_bias, + )(inputs) + return proj + + def out_projection(self, output_dim: int, out: Array) -> Array: + """output projection""" + out_proj = DenseGeneral( + features=output_dim, + axis=(-2, -1), + kernel_init=self.kernel_init, + kernel_axes=('heads', 'kv', 'embed'), + dtype=self.dtype, + weight_dtype=self.weight_dtype, + name='out', + quant=self.quant, + use_bias=self.use_bias, + )(out) + return out_proj + + @nn.compact + def __call__(self, + inputs_q: Array, + decoder_segment_ids: Array | None = None, + *, + model_mode: str = common_types.MODEL_MODE_TRAIN, + deterministic: bool = False): + if self.fused_qkv: + query, key, value = self.qkv_projection(inputs_q, proj_name='qkv_proj') + else: + query = self.projection(inputs_q, proj_name='query') + key = self.projection(inputs_q, proj_name='key') + value = self.projection(inputs_q, proj_name='value') + + depth_scaling = jnp.sqrt(self.head_dim).astype(self.dtype) + query /= depth_scaling + + # annotate with sharding constraint. + query = nn.with_logical_constraint(query, self.query_axis_names) + query = checkpoint_name(query, 'query_proj') + key = nn.with_logical_constraint(key, self.key_axis_names) + key = checkpoint_name(key, 'key_proj') + value = nn.with_logical_constraint(value, self.value_axis_names) + value = checkpoint_name(value, 'value_proj') + + attention_op = AttentionOp(mesh=self.mesh, + attention_kernel=self.attention_kernel, + max_target_length=self.max_target_length, + float32_qk_product=self.float32_qk_product, + float32_logits=self.float32_logits, + quant=self.quant, + quantize_kvcache=self.config.quantize_kvcache, + num_query_heads=self.num_heads, + num_kv_heads=self.num_heads, + dtype=self.dtype) + + out = attention_op(query, key, value, decoder_segment_ids, model_mode) + + out = nn.with_logical_constraint(out, self.out_axis_names) + + # apply output projection, output dim is set to the input dim. + out = self.out_projection(inputs_q.shape[-1], out) + out = checkpoint_name(out, 'out_proj') + return out + + +#----------------------------------------- +# The Decoder Layer specific for GPT3 +#----------------------------------------- + +class Gpt3DecoderLayer(nn.Module): + """Transformer decoder layer that attends to the encoder.""" + config: models.Config + mesh: Mesh + quant: Optional[Quant] = None + + @nn.compact + def __call__(self, + inputs, + decoder_segment_ids, + decoder_positions, + deterministic, + model_mode, + ): + cfg = self.config + mesh = self.mesh + + inputs = nn.with_logical_constraint( + inputs, ('activation_batch', 'activation_length', 'activation_embed')) + + + lnx_layer_norm = Gpt3LayerNorm( + dtype=cfg.dtype, + name='pre_self_attention_norm', + kernel_axes=('embed',), + epsilon=cfg.normalization_layer_epsilon, + reductions_in_fp32=False, + use_bias=True, + ) + lnx = lnx_layer_norm(inputs) + + lnx = nn.with_logical_constraint( + lnx, ('activation_batch', 'activation_length', 'activation_embed')) + + # Self-attention block + assert cfg.num_query_heads == cfg.num_kv_heads, \ + f"{cfg.num_query_heads=} should be the same as {cfg.num_kv_heads=} in gpt3" + attention_layer = Gpt3MultiHeadAttention( + config=cfg, + num_heads=cfg.num_query_heads, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + head_dim=cfg.head_dim, + max_target_length=cfg.max_target_length, + max_prefill_predict_length=cfg.max_prefill_predict_length, + attention_kernel=cfg.attention, + mesh=mesh, + dropout_rate=cfg.dropout_rate, + name='self_attention', + fused_qkv=cfg.fused_qkv, + use_bias=True, + quant=self.quant) + + attention_lnx = attention_layer( + lnx, + decoder_segment_ids=decoder_segment_ids, + model_mode=model_mode, + deterministic=deterministic) + + attention_lnx = nn.with_logical_constraint( + attention_lnx, + ('activation_batch', 'activation_length', 'activation_embed')) + attention_lnx += inputs + + # MLP block. + mlp_lnx = linears.MlpBlock( + intermediate_dim=cfg.mlp_dim, + activations=cfg.mlp_activations, + intermediate_dropout_rate=cfg.dropout_rate, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='mlp', + use_bias=True, + use_pre_norm=True, + config=cfg, + quant=self.quant, + )(attention_lnx, deterministic=deterministic) + mlp_lnx = nn.with_logical_constraint( + mlp_lnx, ('activation_batch', 'activation_length', 'activation_embed') + ) + + layer_output = attention_lnx + mlp_lnx + + layer_output = nn.Dropout( + rate=cfg.dropout_rate, broadcast_dims=(-2,))( + layer_output, deterministic=deterministic) + + layer_output = nn.with_logical_constraint( + layer_output, + ('activation_batch', 'activation_length', 'activation_embed'), + ) + + if cfg.record_internal_nn_metrics: + self.sow('intermediates', 'activation_mean', jnp.mean(layer_output)) + self.sow('intermediates', 'activation_stdev', jnp.std(layer_output)) + self.sow( + 'intermediates', + 'activation_fraction_zero', + jnp.sum(layer_output == 0) / jnp.size(layer_output), + ) + + if cfg.scan_layers: + return layer_output, None + else: + return layer_output diff --git a/maxtext-setup/maxtext/MaxText/layers/initializers.py b/maxtext-setup/maxtext/MaxText/layers/initializers.py new file mode 100644 index 0000000000000000000000000000000000000000..6f0bb9c2324eb31a086ffa9d0ed2e55b39ea51eb --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/initializers.py @@ -0,0 +1,50 @@ +# Copyright 2023 Google LLC + +# 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. + +"""Initializers.""" + +from typing import Callable, Tuple, Union + +from flax import linen as nn +import jax +import common_types + +Array = common_types.Array +DType = common_types.DType +PRNGKey = common_types.PRNGKey +Shape = common_types.Shape + +Initializer = Callable[[PRNGKey, Shape, DType], Array] +InitializerAxis = Union[int, Tuple[int, ...]] +NdInitializer = Callable[ + [PRNGKey, Shape, DType, InitializerAxis, InitializerAxis], Array +] + +default_embed_init = nn.initializers.variance_scaling( + 1.0, 'fan_in', 'normal', out_axis=0 +) + +default_bias_init = jax.nn.initializers.constant(0.0) + + +def nd_dense_init(scale, mode, distribution): + """Initializer with in_axis, out_axis set at call time.""" + + def init_fn(key, shape, dtype, in_axis, out_axis): + fn = jax.nn.initializers.variance_scaling( + scale, mode, distribution, in_axis, out_axis + ) + return fn(key, shape, dtype) + + return init_fn diff --git a/maxtext-setup/maxtext/MaxText/layers/linears.py b/maxtext-setup/maxtext/MaxText/layers/linears.py new file mode 100644 index 0000000000000000000000000000000000000000..01ee36a8806c6f65456b77496565d82cd2a534e6 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/linears.py @@ -0,0 +1,314 @@ +# Copyright 2023 Google LLC +# +# 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. + +"""Linear Layers.""" + +import functools +import operator +from typing import Any, Callable, Iterable, Sequence, Tuple, Union, Optional + +import flax.linen as nn +import jax +from jax import lax +import jax.numpy as jnp +import common_types +from layers import initializers +from layers import normalizations +from layers import quantizations +import numpy as np +from jax.ad_checkpoint import checkpoint_name + +Array = common_types.Array +Config = common_types.Config +DType = common_types.DType +NdInitializer = initializers.NdInitializer + +nd_dense_init = initializers.nd_dense_init +bias_init = initializers.default_bias_init + +RMSNorm = normalizations.RMSNorm +Quant = quantizations.AqtQuantization + +def _convert_to_activation_function( + fn_or_string: Union[str, Callable[..., Any]]) -> Callable[..., Any]: + """Convert a string to an activation function.""" + if fn_or_string == 'linear': + return lambda x: x + elif isinstance(fn_or_string, str): + return getattr(nn, fn_or_string) + elif callable(fn_or_string): + return fn_or_string + else: + raise ValueError(f"""Don't know how to convert {fn_or_string} + to an activation function""") + + +def _normalize_axes(axes: Iterable[int], ndim: int) -> Tuple[int]: + # A tuple by convention. len(axes_tuple) then also gives the rank efficiently. + return tuple(ax if ax >= 0 else ndim + ax for ax in axes) + + +def _canonicalize_tuple(x): + if isinstance(x, Iterable): + return tuple(x) + else: + return (x,) + + +class DenseGeneral(nn.Module): + """A linear transformation with flexible axes. + + Attributes: + features: tuple with numbers of output features. + axis: tuple with axes to apply the transformation on. + weight_dtype: the dtype of the weights (default: float32). + dtype: the dtype of the computation (default: float32). + kernel_init: initializer function for the weight matrix. + use_bias: whether to add bias in linear transformation + quant: quantization config, defaults to None implying no quantization. + """ + + features: Union[Iterable[int], int] + axis: Union[Iterable[int], int] = -1 + weight_dtype: DType = jnp.float32 + dtype: DType = jnp.float32 + kernel_init: NdInitializer = nd_dense_init(1.0, 'fan_in', 'truncated_normal') + kernel_axes: Tuple[str, ...] = () + quant: Optional[Quant] = None + use_bias: bool = False + + @nn.compact + def __call__(self, inputs: Array) -> Array: + """Applies a linear transformation to the inputs along multiple dimensions. + + Args: + inputs: The nd-array to be transformed. + + Returns: + The transformed input. + """ + + def compute_dot_general(inputs, kernel, axis, contract_ind): + """Computes a dot_general operation that may be quantized.""" + dot_general = lax.dot_general + if self.quant: + dot_general_cls = self.quant.dot_general_cls() + dot_general = dot_general_cls() + return dot_general( + inputs, kernel, ((axis, contract_ind), ((), ())), precision=None) + + features = _canonicalize_tuple(self.features) + axis = _canonicalize_tuple(self.axis) + + inputs = jnp.asarray(inputs, self.dtype) + axis = _normalize_axes(axis, inputs.ndim) + + kernel_shape = tuple(inputs.shape[ax] for ax in axis) + features + kernel_in_axis = np.arange(len(axis)) + kernel_out_axis = np.arange(len(axis), len(axis) + len(features)) + if quantizations.in_serve_mode(self.quant): + # During aqt convert state we delete kernel weight from params to save memory. + # Instead they are retreived from the tensors stored in the 'aqt' collection. + kernel = jnp.zeros(kernel_shape) + else: + kernel = self.param( + 'kernel', + nn.with_logical_partitioning(self.kernel_init, self.kernel_axes), + kernel_shape, + self.weight_dtype, + kernel_in_axis, + kernel_out_axis, + ) + kernel = jnp.asarray(kernel, self.dtype) + + contract_ind = tuple(range(0, len(axis))) + output = compute_dot_general(inputs, kernel, axis, contract_ind) + + if self.use_bias: + bias_axes, bias_shape = self.kernel_axes[-len(features):], kernel_shape[-len(features):] + bias = self.param( + 'bias', + nn.with_logical_partitioning(bias_init, bias_axes), + bias_shape, + self.weight_dtype, + ) + bias = jnp.asarray(bias, self.dtype) + output += bias + return output + + +class MlpBlock(nn.Module): + """Transformer MLP / feed-forward block. + + Attributes: + intermediate_dim: Shared dimension of hidden layers. + activations: Type of activations for each layer. Each element is either + 'linear', a string function name in flax.linen, or a function. + kernel_init: Kernel function, passed to the dense layers. + deterministic: Whether the dropout layers should be deterministic. + intermediate_dropout_rate: Dropout rate used after the intermediate layers. + dtype: computation data type for the dense layer. + weight_dtype: weight data type for the dense layer. + use_bias: whether to add bias in all feedforward layers. + use_pre_norm: whether to add pre layer norm in mlp layers. + quant: Optional quantization config, no quantization if None. + """ + + config: Config + intermediate_dim: int = 2048 + activations: Sequence[Union[str, Callable[..., Any]]] = ('relu',) + kernel_init: NdInitializer = nd_dense_init(1.0, 'fan_in', 'truncated_normal') + intermediate_dropout_rate: float = 0.1 + dtype: Any = jnp.float32 + weight_dtype: Any = jnp.float32 + use_bias: bool = False + use_pre_norm: bool = False + quant: Optional[Quant] = None + + def get_norm_layer(self): + if self.config.decoder_block in ("default", "llama2", "mistral", "gemma"): + return RMSNorm + elif self.config.decoder_block == "gpt3": + from layers import gpt3 + return functools.partial(gpt3.Gpt3LayerNorm, reductions_in_fp32=False, use_bias=self.use_bias) + else: + raise ValueError(f"Incorrect decoder_block name {self.config.decoder_block=}") + + @nn.compact + def __call__(self, inputs, decode: bool = False, deterministic: bool = False): + """Applies Transformer MlpBlock module.""" + cfg = self.config + + if self.use_pre_norm: + inputs = self.get_norm_layer()( + name='mlp_layer_norm', + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + kernel_axes=('embed',), + epsilon=cfg.normalization_layer_epsilon, + )(inputs) + + # Iterate over specified MLP input activation functions. + # e.g. ('relu',) or ('gelu', 'linear') for gated-gelu. + activations = [] + if cfg.fused_mlp: + x = DenseGeneral( + (len(self.activations), self.intermediate_dim), + dtype=self.dtype, + weight_dtype=self.weight_dtype, + kernel_init=self.kernel_init, + kernel_axes=('embed', 'num_activations', 'mlp'), + name='wi', + quant=self.quant, + use_bias=self.use_bias, + )(inputs) + for idx, act_fn in enumerate(self.activations): + y = _convert_to_activation_function(act_fn)(x[:,:,idx,...]) + activations.append(y) + else: + for idx, act_fn in enumerate(self.activations): + dense_name = 'wi' if len(self.activations) == 1 else f'wi_{idx}' + x = DenseGeneral( + self.intermediate_dim, + dtype=self.dtype, + weight_dtype=self.weight_dtype, + kernel_init=self.kernel_init, + kernel_axes=('embed', 'mlp'), + name=dense_name, + quant=self.quant, + use_bias=self.use_bias, + )(inputs) + x = _convert_to_activation_function(act_fn)(x) + activations.append(x) + + # Take elementwise product of above intermediate activations. + x = functools.reduce(operator.mul, activations) + x = checkpoint_name(x, 'mlpwi') + # Apply dropout and final dense output projection. + x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))( + x, deterministic=deterministic + ) # Broadcast along length. + x = nn.with_logical_constraint( + x, ('activation_batch', 'activation_length', 'activation_mlp') + ) + output = DenseGeneral( + inputs.shape[-1], + dtype=self.dtype, + weight_dtype=self.weight_dtype, + kernel_init=self.kernel_init, + kernel_axes=('mlp', 'embed'), + name='wo', + quant=self.quant, + use_bias=self.use_bias, + )(x) + + output = checkpoint_name(output, 'mlpwo') + return output + + +class MoeBlock(nn.Module): + """Mixture of Experts (MoE) block. + + Attributes: + num_experts: Number of experts. + num_experts_per_tok: Number of experts for each token. + kernel_init: Kernel function, passed to the dense layers. + kernel_axes: Tuple with axes to apply kernel function. + dtype: Type for the dense layer. + """ + + config: Config + num_experts: int + num_experts_per_tok: int + kernel_init: NdInitializer + kernel_axes: Tuple[str, ...] + dtype: DType = jnp.float32 + + @nn.compact + def __call__(self, inputs, deterministic: bool = False): + gate_logits = DenseGeneral( + self.num_experts, + dtype=self.dtype, + kernel_init=self.kernel_init, + kernel_axes=self.kernel_axes, + name='gate')(inputs) + + weights, selected_experts = lax.top_k(gate_logits, self.num_experts_per_tok) + weights = jax.nn.softmax(weights.astype(jnp.float32), axis=-1) + mlp_lnx = jnp.zeros_like(inputs) + weights = weights.astype(self.dtype) + mlp_lnx = nn.with_logical_constraint( + mlp_lnx, ('activation_batch', 'activation_length', 'activation_embed') + ) + + # TODO(ranran): have a better solution to remove the loop here + for k in range(self.num_experts): + weights_exp = jnp.sum(jnp.multiply(selected_experts==k, weights), axis=-1) + mlp_lnx_exp = MlpBlock( + intermediate_dim=self.config.mlp_dim, + activations=self.config.mlp_activations, + intermediate_dropout_rate=self.config.dropout_rate, + dtype=self.dtype, + weight_dtype=self.weight_dtype, + name=f'mlp_{k}', + config=self.config, + )(inputs, deterministic=deterministic) + + mlp_lnx_exp = nn.with_logical_constraint( + mlp_lnx_exp, ('activation_batch', 'activation_length', 'activation_embed') + ) + mlp_lnx_exp = weights_exp[:, :, None] * mlp_lnx_exp + mlp_lnx += mlp_lnx_exp + + return mlp_lnx diff --git a/maxtext-setup/maxtext/MaxText/layers/llama2.py b/maxtext-setup/maxtext/MaxText/layers/llama2.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0fd1861ecb5e21e82372f0e0cb88a72c37c013 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/llama2.py @@ -0,0 +1,166 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Transformer model definition.""" +# pylint: disable=arguments-differ +# pylint: disable=no-name-in-module + +from flax import linen as nn +from jax.sharding import Mesh +import jax.numpy as jnp +# from jax.experimental.pallas.ops.tpu import flash_attention +from layers import attentions +from layers import embeddings +from layers import linears +from layers import normalizations +from layers import models +from layers import quantizations + +import common_types +from typing import Optional + +Array = common_types.Array +Config = common_types.Config +DType = common_types.DType +Mesh = common_types.Mesh +ScanIn = common_types.ScanIn + +Embed = embeddings.Embed +Attention = attentions.Attention +RMSNorm = normalizations.RMSNorm +Quant = quantizations.AqtQuantization + +#----------------------------------------- +# The Decoder Layer specific for Llama2 +#----------------------------------------- + + +class LlamaDecoderLayer(nn.Module): + """Transformer decoder layer that attends to the encoder.""" + config: models.Config + mesh: Mesh + quant: Optional[Quant] = None + + @nn.compact + def __call__(self, + inputs, + decoder_segment_ids, + decoder_positions, + deterministic, + model_mode, + ): + cfg = self.config + mesh = self.mesh + + inputs = nn.with_logical_constraint( + inputs, ('activation_batch', 'activation_length', 'activation_embed')) + + + lnx_rms = models.RMSNorm( + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='pre_self_attention_layer_norm', + kernel_axes=('embed',), + epsilon=cfg.normalization_layer_epsilon, + ) + lnx = lnx_rms(inputs) + + lnx = nn.with_logical_constraint( + lnx, ('activation_batch', 'activation_length', 'activation_embed')) + + # Self-attention block + attention_layer = Attention( + config = cfg, + num_query_heads=cfg.num_query_heads, + num_kv_heads=cfg.num_kv_heads, + head_dim=cfg.head_dim, + max_target_length=cfg.max_target_length, + max_prefill_predict_length=cfg.max_prefill_predict_length, + attention_kernel=cfg.attention, + mesh=mesh, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + dropout_rate=cfg.dropout_rate, + name='self_attention', + quant=self.quant, + quantize_kvcache=cfg.quantize_kvcache) + + attention_lnx = attention_layer( + lnx, + lnx, + decoder_positions, + decoder_segment_ids=decoder_segment_ids, + deterministic=deterministic, + model_mode=model_mode) + + attention_lnx = nn.with_logical_constraint( + attention_lnx, + ('activation_batch', 'activation_length', 'activation_embed')) + intermediate_inputs = inputs + attention_lnx + + # Fully Connected + hidden_states = models.RMSNorm( + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='post_self_attention_layer_norm', + kernel_axes=('embed',), + epsilon=cfg.normalization_layer_epsilon, + )(intermediate_inputs) + hidden_states = nn.with_logical_constraint( + hidden_states, + ('activation_batch', 'activation_length', 'activation_embed') + ) + + # MLP block. + mlp_lnx = linears.MlpBlock( + intermediate_dim=cfg.mlp_dim, + activations=cfg.mlp_activations, + intermediate_dropout_rate=cfg.dropout_rate, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='mlp', + config=cfg, + quant=self.quant, + )(hidden_states, deterministic=deterministic) + mlp_lnx = nn.with_logical_constraint( + mlp_lnx, ('activation_batch', 'activation_length', 'activation_embed') + ) + + + layer_output = mlp_lnx + intermediate_inputs + + layer_output = nn.Dropout( + rate=cfg.dropout_rate, broadcast_dims=(-2,))( + layer_output, deterministic=deterministic) + + layer_output = nn.with_logical_constraint( + layer_output, + ('activation_batch', 'activation_length', 'activation_embed'), + ) + + if cfg.record_internal_nn_metrics: + self.sow('intermediates', 'activation_mean', jnp.mean(layer_output)) + self.sow('intermediates', 'activation_stdev', jnp.std(layer_output)) + self.sow( + 'intermediates', + 'activation_fraction_zero', + jnp.sum(layer_output == 0) / jnp.size(layer_output), + ) + + if cfg.scan_layers: + return layer_output, None + else: + return layer_output diff --git a/maxtext-setup/maxtext/MaxText/layers/mistral.py b/maxtext-setup/maxtext/MaxText/layers/mistral.py new file mode 100644 index 0000000000000000000000000000000000000000..2992cf5abfb261af266846e5adbc8b3a1b1e0cd5 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/mistral.py @@ -0,0 +1,207 @@ +""" + Copyright 2024 Google LLC + + 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. + """ + +"""Transformer model definition.""" +# pylint: disable=arguments-differ +# pylint: disable=no-name-in-module + + +from typing import Optional +from layers import quantizations +from layers import linears +from layers import initializers +import jax +from jax.sharding import Mesh +from flax import linen as nn +import jax.numpy as jnp +from layers import attentions +from layers import embeddings +from layers import normalizations +from layers import models +import common_types + +Array = common_types.Array +Config = common_types.Config +DType = common_types.DType +Mesh = common_types.Mesh +ScanIn = common_types.ScanIn + +Embed = embeddings.Embed +Attention = attentions.Attention +RMSNorm = normalizations.RMSNorm +Quant = quantizations.AqtQuantization + +# ----------------------------------------- +# The Decoder Layer for Mistral or Mixtral +# ----------------------------------------- + + +class MistralDecoderLayer(nn.Module): + """Transformer decoder layer that attends to the encoder.""" + config: models.Config + mesh: Mesh + quant: Optional[Quant] = None + + @nn.compact + def __call__(self, + inputs, + decoder_segment_ids, + decoder_positions, + deterministic, + model_mode, + ): + cfg = self.config + mesh = self.mesh + + inputs = nn.with_logical_constraint( + inputs, ('activation_batch', 'activation_length', 'activation_embed')) + + lnx_rms = models.RMSNorm( + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='pre_self_attention_layer_norm', + kernel_axes=('embed',), + epsilon=cfg.normalization_layer_epsilon + ) + lnx = lnx_rms(inputs) + + lnx = nn.with_logical_constraint( + lnx, ('activation_batch', 'activation_length', 'activation_embed')) + + # Self-attention block + attention_layer = Attention( + config = cfg, + num_query_heads=cfg.num_query_heads, + num_kv_heads=cfg.num_kv_heads, + head_dim=cfg.head_dim, + max_target_length=cfg.max_target_length, + max_prefill_predict_length=cfg.max_prefill_predict_length, + attention_kernel=cfg.attention, + mesh=mesh, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + dropout_rate=cfg.dropout_rate, + name='self_attention', + quant=self.quant, + quantize_kvcache=cfg.quantize_kvcache) + + attention_lnx = attention_layer( + lnx, + lnx, + decoder_positions, + decoder_segment_ids=decoder_segment_ids, + deterministic=deterministic, + model_mode=model_mode) + + attention_lnx = nn.with_logical_constraint( + attention_lnx, + ('activation_batch', 'activation_length', 'activation_embed')) + intermediate_inputs = inputs + attention_lnx + + # Fully Connected + hidden_states = models.RMSNorm( + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='post_self_attention_layer_norm', + kernel_axes=('embed',), + epsilon=cfg.normalization_layer_epsilon, + )(intermediate_inputs) + hidden_states = nn.with_logical_constraint(hidden_states, ('activation_batch', 'activation_length', 'activation_embed')) + + if cfg.num_experts > 1: + # TODO(ranran): currently, this MoeBlock does not work as expected, and plan to fix it in coming PR. + + # mlp_lnx = linears.MoeBlock( + # config=cfg, + # num_experts=cfg.num_experts, + # num_experts_per_tok=cfg.num_experts_per_tok, + # kernel_init=initializers.nd_dense_init(1.0, 'fan_in', 'truncated_normal'), + # kernel_axes=('embed', 'mlp'), + # dtype=cfg.dtype, + # )(hidden_states, deterministic=deterministic) + + gate_logits = linears.DenseGeneral( + cfg.num_experts, + weight_dtype=cfg.weight_dtype, + dtype=cfg.dtype, + kernel_init=initializers.nd_dense_init( + 1.0, 'fan_in', 'truncated_normal'), + kernel_axes=('embed', 'mlp'), + name="gate", + quant=self.quant, + )(hidden_states) + weights, selected_experts = jax.lax.top_k(gate_logits, cfg.num_experts_per_tok) + weights = jax.nn.softmax(weights.astype(jnp.float32), axis=-1) + mlp_lnx = jnp.zeros_like(hidden_states) + weights = weights.astype(cfg.dtype) + mlp_lnx = nn.with_logical_constraint( + mlp_lnx, ('activation_batch', 'activation_length', 'activation_embed') + ) + + # TODO(ranran): have a better solution to remove the loop here + for k in range(cfg.num_experts): + weights_exp = jnp.sum(jnp.multiply( + selected_experts == k, weights), axis=-1) + mlp_lnx_exp = linears.MlpBlock( + intermediate_dim=cfg.mlp_dim, + activations=cfg.mlp_activations, + intermediate_dropout_rate=cfg.dropout_rate, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name=f'mlp_{k}', + config=cfg, + )(hidden_states, deterministic=deterministic) + mlp_lnx_exp = nn.with_logical_constraint( + mlp_lnx_exp, ('activation_batch', 'activation_length', 'activation_embed') + ) + mlp_lnx_exp = weights_exp[:, :, None] * mlp_lnx_exp + mlp_lnx += mlp_lnx_exp + else: + mlp_lnx = linears.MlpBlock( + intermediate_dim=cfg.mlp_dim, + activations=cfg.mlp_activations, + intermediate_dropout_rate=cfg.dropout_rate, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='mlp', + config=cfg, + )(hidden_states, deterministic=deterministic) + mlp_lnx = nn.with_logical_constraint( + mlp_lnx, ('activation_batch', 'activation_length', 'activation_embed') + ) + + layer_output = mlp_lnx + intermediate_inputs + layer_output = nn.Dropout( + rate=cfg.dropout_rate, broadcast_dims=(-2,))( + layer_output, deterministic=deterministic) + + layer_output = nn.with_logical_constraint( + layer_output, ('activation_batch', 'activation_length', 'activation_embed'), + ) + + if cfg.record_internal_nn_metrics: + self.sow('intermediates', 'activation_mean', jnp.mean(layer_output)) + self.sow('intermediates', 'activation_stdev', jnp.std(layer_output)) + self.sow( + 'intermediates', + 'activation_fraction_zero', + jnp.sum(layer_output == 0) / jnp.size(layer_output), + ) + + if cfg.scan_layers: + return layer_output, None + else: + return layer_output diff --git a/maxtext-setup/maxtext/MaxText/layers/models.py b/maxtext-setup/maxtext/MaxText/layers/models.py new file mode 100644 index 0000000000000000000000000000000000000000..90ecaad0ef8fd6deff496340d67d2d324f4f814f --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/models.py @@ -0,0 +1,374 @@ +# Copyright 2023 Google LLC +# +# 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. + +"""Transformer models.""" +# pylint: disable=arguments-differ +# pylint: disable=no-name-in-module + +from typing import Callable, Optional + + +from flax import linen as nn +import functools +import jax +import jax.numpy as jnp +import common_types +from layers import attentions +from layers import embeddings +from layers import linears +from layers import normalizations, quantizations + +Array = common_types.Array +Config = common_types.Config +DType = common_types.DType +Mesh = common_types.Mesh +ScanIn = common_types.ScanIn + +Embed = embeddings.Embed +Attention = attentions.Attention +RMSNorm = normalizations.RMSNorm +PositionalEmbedding = embeddings.PositionalEmbedding +Quant = quantizations.AqtQuantization + +#------------------------------------------------------------------------------ +# The network: Decoder & Transformer Definitions +#------------------------------------------------------------------------------ + + +class DecoderLayer(nn.Module): + """Transformer decoder layer that attends to the encoder.""" + config: Config + mesh: Mesh + quant: Optional[Quant] = None + + @nn.compact + def __call__(self, + inputs, + decoder_segment_ids, + decoder_positions, + deterministic, + model_mode, + ): + cfg = self.config + mesh = self.mesh + + inputs = nn.with_logical_constraint( + inputs, ('activation_batch', 'activation_length', 'activation_embed')) + + # inputs: embedded inputs to the decoder with shape [batch, length, emb_dim] + lnx = RMSNorm( + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='pre_self_attention_norm', + epsilon=cfg.normalization_layer_epsilon, + kernel_axes=('embed',))(inputs) + lnx = nn.with_logical_constraint( + lnx, ('activation_batch', 'activation_length', 'activation_embed')) + + attention_layer = Attention( + config = self.config, + num_query_heads=cfg.num_query_heads, + num_kv_heads=cfg.num_kv_heads, + head_dim=cfg.head_dim, + max_target_length=cfg.max_target_length, + max_prefill_predict_length=cfg.max_prefill_predict_length, + attention_kernel=cfg.attention, + mesh=mesh, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + dropout_rate=cfg.dropout_rate, + name='self_attention', + quant=self.quant, + quantize_kvcache=self.quantize_kvcache) + + + attention_lnx = attention_layer( + lnx, + lnx, + decoder_positions, + decoder_segment_ids=decoder_segment_ids, + deterministic=deterministic, + model_mode=model_mode) + + attention_lnx = nn.with_logical_constraint( + attention_lnx, + ('activation_batch', 'activation_length', 'activation_embed')) + + # MLP block. + mlp_lnx = linears.MlpBlock( + intermediate_dim=cfg.mlp_dim, + activations=cfg.mlp_activations, + intermediate_dropout_rate=cfg.dropout_rate, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='mlp', + config=cfg, + quant=self.quant, + )(lnx, deterministic=deterministic) + mlp_lnx = nn.with_logical_constraint( + mlp_lnx, ('activation_batch', 'activation_length', 'activation_embed') + ) + + next_layer_addition = mlp_lnx + attention_lnx + + next_layer_addition_dropped_out = nn.Dropout( + rate=cfg.dropout_rate, broadcast_dims=(-2,) + )(next_layer_addition, deterministic=deterministic) + + layer_output = next_layer_addition_dropped_out + inputs + layer_output = nn.with_logical_constraint( + layer_output, + ('activation_batch', 'activation_length', 'activation_embed'), + ) + + if cfg.record_internal_nn_metrics: + self.sow('intermediates', 'activation_mean', jnp.mean(layer_output)) + self.sow('intermediates', 'activation_stdev', jnp.std(layer_output)) + self.sow( + 'intermediates', + 'activation_fraction_zero', + jnp.sum(layer_output == 0) / jnp.size(layer_output), + ) + + if cfg.scan_layers: + return layer_output, None + + if cfg.scan_layers: + return layer_output, None + else: + return layer_output + + +class Decoder(nn.Module): + """A stack of decoder layers as a part of an encoder-decoder architecture.""" + config: Config + shared_embedding: nn.Module + mesh: Mesh + quant: Optional[Quant] = None + + def get_decoder_layer(self): + if self.config.decoder_block == "default": + return DecoderLayer + elif self.config.decoder_block == "llama2": + from layers import llama2 + return llama2.LlamaDecoderLayer + elif self.config.decoder_block == "mistral": + # TODO(ranran): update to Mistral with sliding window attention + from layers import mistral + return mistral.MistralDecoderLayer + elif self.config.decoder_block == "gemma": + from layers import gemma + return gemma.GemmaDecoderLayer + elif self.config.decoder_block == "gpt3": + from layers import gpt3 + return gpt3.Gpt3DecoderLayer + else: + raise ValueError(f"Incorrect decoder_block name {self.config.decoder_block=}") + + def get_norm_layer(self): + if self.config.decoder_block in ("default", "llama2", "mistral", "gemma"): + return RMSNorm + elif self.config.decoder_block == "gpt3": + from layers import gpt3 + return functools.partial(gpt3.Gpt3LayerNorm, reductions_in_fp32=False, use_bias=True) + else: + raise ValueError(f"Incorrect decoder_block name {self.config.decoder_block=}") + + @nn.compact + def __call__(self, + decoder_input_tokens, + decoder_positions, + decoder_segment_ids=None, + deterministic=False, + model_mode=common_types.MODEL_MODE_TRAIN, + ): + cfg = self.config + mesh = self.mesh + assert decoder_input_tokens.ndim == 2 # [batch, len] + + # [batch, length] -> [batch, length, emb_dim] + y = self.shared_embedding(decoder_input_tokens.astype('int32')) + y = nn.Dropout( + rate=cfg.dropout_rate, broadcast_dims=(-2,))( + y, deterministic=deterministic) + y = y.astype(cfg.dtype) + + if cfg.use_untrainable_positional_embedding: + y = PositionalEmbedding(cfg.base_emb_dim)(y, decoder_positions) + + if cfg.trainable_position_size > 0: + y += Embed( + num_embeddings=cfg.trainable_position_size, + features=cfg.emb_dim, + dtype=cfg.dtype, + embedding_init=nn.initializers.normal(stddev=1.0), + name='position_embedder', + config=cfg)(decoder_positions) + + BlockLayer = self.get_decoder_layer() + + if cfg.remat_policy != 'none': + if cfg.remat_policy == 'minimal': + policy = jax.checkpoint_policies.checkpoint_dots_with_no_batch_dims + elif cfg.remat_policy == 'save_dot_except_mlpwi': + policy = jax.checkpoint_policies.save_only_these_names( + 'query_proj', 'value_proj', 'key_proj', 'qkv_proj', 'out_proj', 'mlpwo', + ) + elif cfg.remat_policy == 'save_dot_except_mlp': + policy = jax.checkpoint_policies.save_only_these_names( + 'query_proj', 'value_proj', 'key_proj', 'qkv_proj', 'out_proj', + ) + elif cfg.remat_policy == 'save_qkv_proj': + policy = jax.checkpoint_policies.save_only_these_names( + 'query_proj', 'value_proj', 'key_proj', 'qkv_proj', + ) + elif cfg.remat_policy == 'minimal_offloaded': + policy = jax.checkpoint_policies.offload_dot_with_no_batch_dims(offload_src="device", offload_dst="pinned_host") + else: + assert ( + cfg.remat_policy == 'full' + ), 'Remat policy needs to be on list of remat policies' + policy = None + BlockLayer = nn.remat( # pylint: disable=invalid-name + BlockLayer, + prevent_cse=not cfg.scan_layers, + policy=policy, + static_argnums=(-1, -2, -3, -4, -5), + ) + if cfg.scan_layers: + initializing = self.is_mutable_collection('params') + params_spec = ( + cfg.param_scan_axis if initializing else ScanIn(cfg.param_scan_axis) + ) + cache_spec = 0 + y, _ = nn.scan( + BlockLayer, + variable_axes={ + 'params': params_spec, + 'cache': cache_spec, + 'intermediates': 0, + 'aqt':0, + }, + split_rngs={ + 'params': True, + 'dropout': cfg.enable_dropout, + }, + in_axes=( + nn.broadcast, + nn.broadcast, + nn.broadcast, + nn.broadcast, + ), + length=cfg.num_decoder_layers, + metadata_params={nn.PARTITION_NAME: 'layers'}, + )(config=cfg, mesh=mesh, name='layers', quant=self.quant)( + y, + decoder_segment_ids, + decoder_positions, + deterministic, + model_mode, + ) + else: + for lyr in range(cfg.num_decoder_layers): + y = BlockLayer(config=cfg, mesh=mesh, name=f'layers_{lyr}', + quant=self.quant)( + y, + decoder_segment_ids, + decoder_positions, + deterministic, + model_mode, + ) + + y = self.get_norm_layer()( + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + name='decoder_norm', + epsilon=cfg.normalization_layer_epsilon, + kernel_axes=('embed',), + )(y) + y = nn.Dropout(rate=cfg.dropout_rate, broadcast_dims=(-2,))( + y, deterministic=deterministic + ) + + # [batch, length, emb_dim] -> [batch, length, vocab_size] + if cfg.logits_via_embedding: + # Use the transpose of embedding matrix for logit transform. + logits = self.shared_embedding.attend(y) + if self.config.normalize_embedding_logits: + # Correctly normalize pre-softmax logits for this shared case. + logits = logits / jnp.sqrt(y.shape[-1]) + else: + logits = linears.DenseGeneral( + cfg.vocab_size, + weight_dtype=cfg.weight_dtype, + dtype=jnp.float32 if cfg.logits_dot_in_fp32 else cfg.dtype, # for logit training stability + kernel_axes=('embed', 'vocab'), + name='logits_dense')(y) # We do not quantize the logits matmul. + logits = nn.with_logical_constraint( + logits, ('activation_batch', 'activation_length', 'activation_vocab')) + logits = logits.astype(jnp.float32) + return logits + + +class Transformer(nn.Module): + """An decoder-only Transformer model.""" + # Make new attributes required, so that all Transformer dependencies (train, decode, compile, etc) will error instead of silently use defaults. + # pylint: disable=attribute-defined-outside-init + config: Config + mesh: Mesh + quant: Quant + + def setup(self): + """Initialize shared_embedding & decoder layers.""" + + cfg = self.config + mesh = self.mesh + self.shared_embedding = Embed( + num_embeddings=cfg.vocab_size, + features=cfg.emb_dim, + dtype=cfg.dtype, + attend_dtype=jnp.float32 if cfg.logits_dot_in_fp32 else cfg.dtype, # for logit training stability + embedding_init=nn.initializers.normal(stddev=1.0), + name='token_embedder', + config=cfg, + ) + + self.decoder = Decoder( + config=cfg, shared_embedding=self.shared_embedding, + mesh=mesh, quant=self.quant + ) + + def __call__( + self, + decoder_input_tokens, + decoder_positions, + decoder_segment_ids=None, + enable_dropout=True, + model_mode=common_types.MODEL_MODE_TRAIN + ): + """Applies Transformer decoder-branch on encoded-input and target.""" + + if decoder_segment_ids is not None and model_mode == common_types.MODEL_MODE_AUTOREGRESSIVE: + raise ValueError( + f'During autoregressive decoding we assume the tokens are in the active sequence' + f' which is always {common_types.DECODING_ACTIVE_SEQUENCE_INDICATOR}.') + + logits = self.decoder( + decoder_input_tokens=decoder_input_tokens, + decoder_positions=decoder_positions, + decoder_segment_ids=decoder_segment_ids, + deterministic=not enable_dropout, + model_mode=model_mode, + ) + return logits diff --git a/maxtext-setup/maxtext/MaxText/layers/normalizations.py b/maxtext-setup/maxtext/MaxText/layers/normalizations.py new file mode 100644 index 0000000000000000000000000000000000000000..6d451d4fe28b9e14c4531de58bbe845df2d3b22a --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/normalizations.py @@ -0,0 +1,50 @@ +# Copyright 2023 Google LLC +# +# 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. + +"""Normalization Layers.""" + +from typing import Any, Tuple + +from flax import linen as nn +from jax import lax +import jax.numpy as jnp +from layers import initializers + +Initializer = initializers.Initializer + + +class RMSNorm(nn.Module): + """RMS normalization.""" + epsilon: float = 1e-6 + dtype: Any = jnp.float32 + weight_dtype: Any = jnp.float32 + kernel_axes: Tuple[str, ...] = () + scale_init: Initializer = nn.initializers.ones + + @nn.compact + def __call__(self, x: jnp.ndarray) -> jnp.ndarray: + """Applies layer normalization on the input.""" + x = jnp.asarray(x, jnp.float32) + features = x.shape[-1] + mean2 = jnp.mean(lax.square(x), axis=-1, keepdims=True) + y = jnp.asarray(x * lax.rsqrt(mean2 + self.epsilon), self.dtype) + scale = self.param( + 'scale', + nn.with_logical_partitioning(self.scale_init, self.kernel_axes), + (features,), + self.weight_dtype, + ) + + scale = jnp.asarray(scale, self.dtype) + return y * scale diff --git a/maxtext-setup/maxtext/MaxText/layers/quantizations.py b/maxtext-setup/maxtext/MaxText/layers/quantizations.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e83a6903e0fb22a5fdf453426eaf25228fba7a --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/layers/quantizations.py @@ -0,0 +1,145 @@ +# Copyright 2024 Google LLC +# +# 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. + +"""Quantization library.""" + +import functools + +from aqt.jax.v2 import config as aqt_config +from aqt.jax.v2.flax import aqt_flax +from common_types import Array, Config +from dataclasses import dataclass +import jax +import jax.numpy as jnp +from jax.tree_util import tree_flatten_with_path, tree_unflatten + +MAX_INT8 = 127.5 + +@dataclass +class AqtQuantization: + """ Configures AQT quantization github.com/google/aqt. """ + quant_dg: aqt_config.DotGeneral + quant_mode: aqt_flax.QuantMode = aqt_flax.QuantMode.TRAIN + + def dot_general_cls(self): + """ Returns dot_general configured with aqt params. """ + aqt_dg_cls = functools.partial( + aqt_flax.AqtDotGeneral, + self.quant_dg, + rhs_quant_mode=self.quant_mode + ) + return aqt_dg_cls + + def einsum(self): + """ Returns einsum configured with aqt params """ + aqt_einsum = functools.partial(aqt_flax.AqtEinsum( + cfg=self.quant_dg, + lhs_quant_mode=self.quant_mode + ) + ) + return aqt_einsum + +def _get_quant_config(config): + """Set quantization params based on user configuration.""" + if not config.quantization or config.quantization == '': + return None + elif config.quantization == "int8": + if config.quantization_local_shard_count == 0: + drhs_bits = None + drhs_accumulator_dtype = None + drhs_local_aqt=None + else: + drhs_bits = 8 + drhs_accumulator_dtype = jnp.int32 + drhs_local_aqt = aqt_config.LocalAqt(config.quantization_local_shard_count) + return aqt_config.config_v3( + fwd_bits=8, + dlhs_bits=8, + drhs_bits=drhs_bits, + rng_type='jax.uniform', + dlhs_local_aqt=None, + drhs_local_aqt=drhs_local_aqt, + fwd_accumulator_dtype=jnp.int32, + dlhs_accumulator_dtype=jnp.int32, + drhs_accumulator_dtype=drhs_accumulator_dtype, + ) + else: + raise ValueError(f'Invalid value configured for quantization {config.quantization}.') + +def in_convert_mode(quant): + return quant and (quant.quant_mode == aqt_flax.QuantMode.CONVERT) + +def in_serve_mode(quant): + return quant and (quant.quant_mode == aqt_flax.QuantMode.SERVE) + +def get_quant_mode(quant_mode_str: str = 'train'): + """ Set quant mode.""" + if quant_mode_str == 'train': + return aqt_flax.QuantMode.TRAIN + elif quant_mode_str == 'serve': + return aqt_flax.QuantMode.SERVE + elif quant_mode_str == 'convert': + return aqt_flax.QuantMode.CONVERT + else: + raise ValueError(f'Invalid quantization mode {quant_mode_str}.') + return None + +def configure_quantization(config: Config, quant_mode_str: str = 'train'): + """ Configure quantization based on user config and quant mode.""" + quant_cfg = _get_quant_config(config) + if quant_cfg: + quant_mode = get_quant_mode(quant_mode_str) + return AqtQuantization(quant_dg=quant_cfg, quant_mode=quant_mode) + return None + +def _get_aqt_key_paths(aqt_vars): + """ Generate a list of paths which have aqt state """ + aqt_tree_flat, _ = jax.tree_util.tree_flatten_with_path(aqt_vars) + aqt_key_paths = [] + for k, _ in aqt_tree_flat: + pruned_keys = [] + for d in list(k): + if 'AqtDotGeneral' in d.key: + pruned_keys.append(jax.tree_util.DictKey(key='kernel')) + break + else: + assert 'Aqt' not in d.key, f"Unexpected Aqt op {d.key} in {k}." + pruned_keys.append(d) + aqt_key_paths.append(tuple(pruned_keys)) + return aqt_key_paths + + +def remove_quantized_params(params, aqt_vars): + """Remove param values with aqt tensors to Null to optimize memory.""" + aqt_paths = _get_aqt_key_paths(aqt_vars) + tree_flat, tree_struct = tree_flatten_with_path(params) + for i, (k, v) in enumerate(tree_flat): + if k in aqt_paths: + v = {} + tree_flat[i] = v + return tree_unflatten(tree_struct, tree_flat) + +def configure_kv_quantization(config: Config): + """ Configure kv quantization based on user config.""" + return False if not config.quantize_kvcache else True + +def quantize_kv(kv: Array): + """Quantize key/values stored in kvcache.""" + scale = jnp.max(jnp.abs(kv), axis=-1, keepdims=True) + value = jnp.int8(jnp.rint(kv * (MAX_INT8 / scale))) + return value, scale + +def unquantize_kv(value: Array, scale:Array, dtype:jnp.dtype): + """Unquantize key/values stored in kvcache.""" + return value.astype(dtype) * scale / MAX_INT8 diff --git a/maxtext-setup/maxtext/MaxText/llama_or_mistral_ckpt.py b/maxtext-setup/maxtext/MaxText/llama_or_mistral_ckpt.py new file mode 100644 index 0000000000000000000000000000000000000000..8998c9ec9001596a5b0dbfc0fffaa46e4bf77044 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/llama_or_mistral_ckpt.py @@ -0,0 +1,414 @@ +""" + Copyright 2023 Google LLC + 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. + """ + +r"""Convert weights from a Llama or Mistral model to a MaxText one. + +Usage: + +Get LLaMA pytorch_vars from Meta + +Example cmd: +To save a ckpt +python3 MaxText/llama_or_mistral_ckpt.py --base-model-path \ + --maxtext-model-path --model-size llama2-7b + +For large size model (e.g. 70B model), this script requires large memory VM. +The script load and save weights in a single pass. +To fit less memory, modify convert() to load/save weights in multiple passes. +Each pass, load and save partial weights (subset of all weight variables). +""" +# pylint: disable=g-line-too-long +import argparse +import pathlib + +import numpy as np + +import checkpointing +import jax +from flax.training import train_state +import max_logging +from train import save_checkpoint +import torch +import sys +import os + +jax.config.update('jax_platform_name', 'cpu') + +def permute_to_match_maxtext_rope(arr): + evens = arr[..., ::2] + odds = arr[..., 1::2] + return jax.numpy.concatenate((evens, odds), axis=arr.ndim-1) + + +MODEL_PARAMS_DICT = { + 'llama2-70b': { + 'num_layers': 80, + 'num_heads': 64, + 'num_kv_heads': 8, + 'dims_per_head': 128, + 'vocab': 32000, + }, + 'llama2-13b': { + 'num_layers': 40, + 'num_heads': 40, + 'num_kv_heads': 40, + 'dims_per_head': 128, + 'vocab': 32000, + }, + 'llama2-7b': { + 'num_layers': 32, + 'num_heads': 32, + 'num_kv_heads': 32, + 'dims_per_head': 128, + 'vocab': 32000, + }, + 'mistral-7b': { + 'num_layers': 32, + 'num_heads': 32, + 'num_kv_heads': 8, + 'dims_per_head': 128, + 'vocab': 32000, + 'base_emb_dim': 4096, + 'base_mlp_dim': 14336, + }, + 'mixtral-8x7b': { + 'num_layers': 32, + 'num_heads': 32, + 'num_kv_heads': 8, + 'dims_per_head': 128, + 'vocab': 32000, + 'base_emb_dim': 4096, + 'base_mlp_dim': 14336, + 'num_experts': 8, + }, +} + +SIMULATED_CPU_DEVICES_COUNT = 16 + + +def convert(base_model_path, maxtext_model_path, model_size): + """ + Function to convert the checkpoint at base_model_path into Orbax checkpoint + for MaxText and save at maxtext_model_path + + Attributes: + base_model_path: checkpoint path + maxtext_model_path: Path to save the MaxText checkpoint to + model_size: llama2-7b to 70b, mistral-7b, or mixtral-8x7b + """ + """Convert model to maxtext.""" + model_params = MODEL_PARAMS_DICT[model_size] + base_num_decoder_layers = model_params['num_layers'] + base_num_query_heads = model_params['num_heads'] + head_dim = model_params['dims_per_head'] + base_num_kv_heads = model_params['num_kv_heads'] + vocab_size = model_params['vocab'] + num_experts = model_params['num_experts'] if 'num_experts' in model_params else None + + print(f'Loading the base model from {base_model_path}') + # Skip any hidden files for checkpoints + ckpt_paths = sorted(pathlib.Path(base_model_path).glob('[!.]*.pth')) + pytorch_vars = {} + for i, ckpt_path in enumerate(ckpt_paths): + print(f'Loading checkpoint {i+1} of {len(ckpt_paths)} ...') + checkpoint = torch.load(ckpt_path, map_location='cpu') + pytorch_vars[int(ckpt_path.name.split('.', maxsplit=2)[1])] = checkpoint + pytorch_vars = [pytorch_vars[i] for i in sorted(list(pytorch_vars.keys()))] + + layer_key = 'gate' if num_experts else 'mlp' + jax_weights = { + 'decoder': { + 'layers': { + layer_key: {}, + 'pre_self_attention_layer_norm': {}, + 'post_self_attention_layer_norm': {}, + 'self_attention': {}, + }, + 'decoder_norm': { + 'scale': pytorch_vars[0]['norm.weight'].type(torch.float16).numpy() + }, + 'logits_dense': { + 'kernel': np.concatenate([var['output.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=0).transpose()[:, :vocab_size] + } + }, + 'token_embedder': { + 'embedding': np.concatenate([var['tok_embeddings.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=1)[:vocab_size, :] + + } + + } + + layer_weight = { + 'pre_self_attention_layer_norm': { + 'scale': [] + }, + 'post_self_attention_layer_norm': { + 'scale': [] + } + } + + if num_experts is None: + layer_weight['mlp'] = { + 'wi_0': { + 'kernel': [] + }, + 'wi_1': { + 'kernel': [] + }, + 'wo': { + 'kernel': [] + }, + } + else: + layer_weight['gate'] = { + 'kernel': [] + } + + for k in range(num_experts): + jax_weights['decoder']['layers'][f'mlp_{k}'] = {} + layer_weight[f'mlp_{k}'] = { + 'wi_0': { + 'kernel': [] + }, + 'wi_1': { + 'kernel': [] + }, + 'wo': { + 'kernel': [] + }, + } + + self_attention = { + 'query': { + 'kernel': [] + }, + 'key': { + 'kernel': [] + }, + 'value': { + 'kernel': [] + }, + 'out': { + 'kernel': [] + }, + } + + for layer_idx in range(base_num_decoder_layers): + wq = np.concatenate([var[f'layers.{layer_idx}.attention.wq.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=0).transpose() + wk = np.concatenate([var[f'layers.{layer_idx}.attention.wk.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=0).transpose() + wv = np.concatenate([var[f'layers.{layer_idx}.attention.wv.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=0).transpose() + + wq = np.reshape(wq, [base_num_query_heads * head_dim, + base_num_query_heads, head_dim]) + wk = np.reshape(wk, [base_num_query_heads * head_dim, + base_num_kv_heads, head_dim]) + wv = np.reshape(wv, [base_num_query_heads * head_dim, + base_num_kv_heads, head_dim]) + wq = permute_to_match_maxtext_rope(wq) + wk = permute_to_match_maxtext_rope(wk) + + w_post = np.concatenate( + [ + var[f'layers.{layer_idx}.attention.wo.weight'].type( + torch.float16).numpy() + for var in pytorch_vars + ], + axis=1, + ) + + w_post = np.reshape( + w_post, [base_num_query_heads * head_dim, base_num_query_heads, head_dim]) + + self_attention['query']['kernel'].append(wq) + self_attention['key']['kernel'].append(wk) + self_attention['value']['kernel'].append(wv) + self_attention['out']['kernel'].append(w_post) + pre_self_attention_layernorm = pytorch_vars[0][f'layers.{layer_idx}.attention_norm.weight'].type( + torch.float16).numpy() + post_self_attention_layernorm = pytorch_vars[0][f'layers.{layer_idx}.ffn_norm.weight'].type( + torch.float16).numpy() + layer_weight['pre_self_attention_layer_norm']['scale'].append( + pre_self_attention_layernorm) + layer_weight['post_self_attention_layer_norm']['scale'].append( + post_self_attention_layernorm) + + if num_experts is None: + wi_0 = np.concatenate([var[f'layers.{layer_idx}.feed_forward.w1.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=0).transpose() + wi_1 = np.concatenate([var[f'layers.{layer_idx}.feed_forward.w3.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=0).transpose() + wo = np.concatenate([var[f'layers.{layer_idx}.feed_forward.w2.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=1).transpose() + layer_weight['mlp']['wi_0']['kernel'].append(wi_0) + layer_weight['mlp']['wi_1']['kernel'].append(wi_1) + layer_weight['mlp']['wo']['kernel'].append(wo) + else: + gate = np.concatenate([var[f'layers.{layer_idx}.feed_forward.gate.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=0).transpose() + layer_weight['gate']['kernel'].append(gate) + for k in range(num_experts): + wi_0 = np.concatenate([var[f'layers.{layer_idx}.feed_forward.experts.{k}.w1.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=0).transpose() + wi_1 = np.concatenate([var[f'layers.{layer_idx}.feed_forward.experts.{k}.w3.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=0).transpose() + wo = np.concatenate([var[f'layers.{layer_idx}.feed_forward.experts.{k}.w2.weight'].type(torch.float16).numpy() + for var in pytorch_vars], axis=1).transpose() + layer_weight[f'mlp_{k}']['wi_0']['kernel'].append(wi_0) + layer_weight[f'mlp_{k}']['wi_1']['kernel'].append(wi_1) + layer_weight[f'mlp_{k}']['wo']['kernel'].append(wo) + + self_attention['query']['kernel'] = np.array( + self_attention['query']['kernel']) + self_attention['key']['kernel'] = np.array(self_attention['key']['kernel']) + self_attention['value']['kernel'] = np.array( + self_attention['value']['kernel']) + self_attention['out']['kernel'] = np.array(self_attention['out']['kernel']) + self_attention['query']['kernel'] = np.transpose( + self_attention['query']['kernel'], axes=(1, 0, 2, 3)) + self_attention['key']['kernel'] = np.transpose( + self_attention['key']['kernel'], axes=(1, 0, 2, 3)) + self_attention['value']['kernel'] = np.transpose( + self_attention['value']['kernel'], axes=(1, 0, 2, 3)) + # layers, base_num_query_heads * head_dim, base_num_query_heads, head_dim => + # base_num_query_heads, layers,head_dim, base_num_query_heads * head_dim + self_attention['out']['kernel'] = np.transpose( + self_attention['out']['kernel'], axes=(2, 0, 3, 1)) + + # scale the query weights + self_attention['query']['kernel'] = self_attention['query']['kernel'] / \ + np.sqrt(head_dim) + + jax_weights['decoder']['layers']['self_attention'] = self_attention + + # self attention layer norm and swap the layer index + layer_weight['pre_self_attention_layer_norm']['scale'] = np.array( + layer_weight['pre_self_attention_layer_norm']['scale']) + layer_weight['post_self_attention_layer_norm']['scale'] = np.array( + layer_weight['post_self_attention_layer_norm']['scale']) + layer_weight['pre_self_attention_layer_norm']['scale'] = np.transpose( + layer_weight['pre_self_attention_layer_norm']['scale'], + axes=(1, 0)) + layer_weight['post_self_attention_layer_norm']['scale'] = np.transpose( + layer_weight['post_self_attention_layer_norm']['scale'], + axes=(1, 0)) + + jax_weights['decoder']['layers']['pre_self_attention_layer_norm'] = layer_weight['pre_self_attention_layer_norm'] + jax_weights['decoder']['layers']['post_self_attention_layer_norm'] = layer_weight['post_self_attention_layer_norm'] + + if num_experts is None: + layer_weight['mlp']['wi_0']['kernel'] = np.array( + layer_weight['mlp']['wi_0']['kernel']) + layer_weight['mlp']['wi_1']['kernel'] = np.array( + layer_weight['mlp']['wi_1']['kernel']) + layer_weight['mlp']['wo']['kernel'] = np.array( + layer_weight['mlp']['wo']['kernel']) + # swap the layer index + layer_weight['mlp']['wi_0']['kernel'] = np.transpose( + layer_weight['mlp']['wi_0']['kernel'], axes=(1, 0, 2)) + layer_weight['mlp']['wi_1']['kernel'] = np.transpose( + layer_weight['mlp']['wi_1']['kernel'], axes=(1, 0, 2)) + layer_weight['mlp']['wo']['kernel'] = np.transpose( + layer_weight['mlp']['wo']['kernel'], axes=(1, 0, 2)) + + jax_weights['decoder']['layers']['mlp'] = layer_weight['mlp'] + else: + layer_weight['gate']['kernel'] = np.array(layer_weight['gate']['kernel']) + layer_weight['gate']['kernel'] = np.transpose( + layer_weight['gate']['kernel'], axes=(1, 0, 2)) + jax_weights['decoder']['layers']['gate'] = layer_weight['gate'] + for k in range(num_experts): + layer_weight[f'mlp_{k}']['wi_0']['kernel'] = np.array( + layer_weight[f'mlp_{k}']['wi_0']['kernel']) + layer_weight[f'mlp_{k}']['wi_1']['kernel'] = np.array( + layer_weight[f'mlp_{k}']['wi_1']['kernel']) + layer_weight[f'mlp_{k}']['wo']['kernel'] = np.array( + layer_weight[f'mlp_{k}']['wo']['kernel']) + # swap the layer index + layer_weight[f'mlp_{k}']['wi_0']['kernel'] = np.transpose( + layer_weight[f'mlp_{k}']['wi_0']['kernel'], axes=(1, 0, 2)) + layer_weight[f'mlp_{k}']['wi_1']['kernel'] = np.transpose( + layer_weight[f'mlp_{k}']['wi_1']['kernel'], axes=(1, 0, 2)) + layer_weight[f'mlp_{k}']['wo']['kernel'] = np.transpose( + layer_weight[f'mlp_{k}']['wo']['kernel'], axes=(1, 0, 2)) + + jax_weights['decoder']['layers'][f'mlp_{k}'] = layer_weight[f'mlp_{k}'] + + mesh = jax.sharding.Mesh(jax.devices(), "checkpoint_sharding_axis") + s1=jax.sharding.NamedSharding(mesh,jax.sharding.PartitionSpec("checkpoint_sharding_axis")) #shards first axis + s2=jax.sharding.NamedSharding(mesh,jax.sharding.PartitionSpec(None,"checkpoint_sharding_axis")) #shards second axis + s3=jax.sharding.NamedSharding(mesh,jax.sharding.PartitionSpec(None)) #no sharding + + def checkpoint_device_put(arr): + if arr.shape[0]%SIMULATED_CPU_DEVICES_COUNT==0: + print("sharding first axis") + return jax.device_put(arr, device=s1) + elif len(arr.shape)>1 and arr.shape[1]%SIMULATED_CPU_DEVICES_COUNT==0: + print("sharding second axis") + return jax.device_put(arr, device=s2) + else: + print("no sharding was possible, replicating") + return jax.device_put(arr, device=s3) + + # convert all weights to jax.numpy with sharding if applicable + jax_weights = jax.tree_map(checkpoint_device_put, jax_weights) + + # dummy configs for the checkpoint_manager + step_number_to_save_new_ckpt = 0 + enable_checkpointing = True + async_checkpointing = False + save_interval_steps = 1 + + checkpoint_manager = checkpointing.create_orbax_checkpoint_manager( + maxtext_model_path, + enable_checkpointing, + async_checkpointing, + save_interval_steps + ) + + state_new = train_state.TrainState( + step=0, + apply_fn=None, + params=jax_weights, + tx=None, # type: ignore + opt_state={} + ) + + if checkpoint_manager is not None: + if save_checkpoint(checkpoint_manager, step_number_to_save_new_ckpt, state_new): + max_logging.log( + f"saved a checkpoint at step {step_number_to_save_new_ckpt}") + # Upon preemption, exit when and only when all ongoing saves are complete. + if checkpoint_manager.reached_preemption(0): + checkpoint_manager.wait_until_finished() + sys.exit() + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--base-model-path', type=str, required=True) + parser.add_argument('--maxtext-model-path', type=str, required=True) + parser.add_argument('--model-size', type=str, required=True) + + args = parser.parse_args() + + if args.model_size not in MODEL_PARAMS_DICT: + raise NotImplementedError + + os.environ['XLA_FLAGS'] = f'--xla_force_host_platform_device_count={SIMULATED_CPU_DEVICES_COUNT}' + + convert(args.base_model_path, args.maxtext_model_path, args.model_size) diff --git a/maxtext-setup/maxtext/MaxText/max_logging.py b/maxtext-setup/maxtext/MaxText/max_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..61d984f7be884308cef0020856bac895fb212adc --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/max_logging.py @@ -0,0 +1,20 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Stub for logging utilities. Right now just meant to avoid raw prints""" + +def log(user_str): + print(user_str, flush = True) diff --git a/maxtext-setup/maxtext/MaxText/max_utils.py b/maxtext-setup/maxtext/MaxText/max_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f929f1310089afd730443967f581f8b5964db64a --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/max_utils.py @@ -0,0 +1,601 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Common Max Utils needed by multiple modules""" +import checkpointing +import common_types +import functools +import time +import socket + +import max_logging + +import numpy as np +import jax +import jax.numpy as jnp +from jax.experimental import mesh_utils + + +import json +import yaml +import flax +from flax.training import train_state +from flax import linen as nn +from flax.linen import partitioning as nn_partitioning + +import optax +import os +from typing import Tuple +from tensorboardX import writer + +from google.cloud import storage + +def find_nans_and_infs(pytree): + def finder(x): + return jnp.any(jnp.isinf(x) | jnp.isnan(x)) + bad_pytree = jax.tree_map(finder, pytree) + return jax.tree_util.tree_flatten(bad_pytree) + +def l2norm_pytree(x): + """L2 norm of a pytree of arrays.""" + return jax.tree_util.tree_reduce( + lambda x, y: x + jax.numpy.sum(jax.numpy.square(y)), x, initializer=0.0 + ) ** 0.5 + +def calculate_num_params_from_pytree(params): + params_sizes = jax.tree_util.tree_map(jax.numpy.size, params) + total_parameters = jax.tree_util.tree_reduce(lambda x, y: x + y, params_sizes) + assert total_parameters >= 0 + return total_parameters + +def calculate_bytes_from_pytree(params): + params_bytes = jax.tree_util.tree_map(lambda x : x.nbytes, params) + total_bytes = jax.tree_util.tree_reduce(lambda x, y: x + y, params_bytes) + return total_bytes + +def summarize_size_from_pytree(params): + num_params = calculate_num_params_from_pytree(params) + num_bytes = calculate_bytes_from_pytree(params) + return num_params, num_bytes, num_bytes/num_params + +def activate_profiler(config, optional_postfix=""): + if config.enable_profiler and (config.upload_all_profiler_results or jax.process_index() == 0): + output_path = os.path.join(config.tensorboard_dir, optional_postfix) + jax.profiler.start_trace(output_path) + +def deactivate_profiler(config): + if config.enable_profiler and (config.upload_all_profiler_results or jax.process_index() == 0): + jax.profiler.stop_trace() + +def initialize_summary_writer(config): + return writer.SummaryWriter(config.tensorboard_dir) if jax.process_index() == 0 else None + +def close_summary_writer(summary_writer): + if jax.process_index() == 0: + summary_writer.close() + +def _prepare_metrics_for_json(metrics, step, run_name): + """Converts metric dictionary into json supported types (e.g. float)""" + metrics_dict = {} + for val in metrics['scalar']: + metrics_dict[val] = float(metrics['scalar'][val]) + metrics_dict['step'] = float(step) + metrics_dict['run_name'] = run_name + return metrics_dict + +def write_metrics_locally(metrics, step, config, file): + """Writes metrics locally for testing""" + if step == 0: + file.truncate(0) + + metrics_dict = _prepare_metrics_for_json(metrics, step, config.run_name) + file.write(str(json.dumps(metrics_dict))+'\n') + + if step == config.steps - 1: + file.close() + +def add_config_to_summary_writer(config, summary_writer): + """Writes config params to tensorboard""" + if jax.process_index() == 0: + for key, value in config.get_keys().items(): + add_text_to_summary_writer(key, str(value), summary_writer) + +def add_text_to_summary_writer(key, value, summary_writer): + """Writes given key-value pair to tensorboard as text/summary""" + if jax.process_index() == 0: + summary_writer.add_text(key, value) + +def write_metrics_for_gcs(metrics, step, config, running_metrics): + """Writes metrics to gcs""" + metrics_dict_step = _prepare_metrics_for_json(metrics, step, config.run_name) + running_metrics.append(metrics_dict_step) + if (step + 1) % config.log_period == 0 or step == config.steps - 1: + start_step = (step // config.log_period) * config.log_period + metrics_filename = f"metrics_step_{start_step:06}_to_step_{step:06}.txt" + with open(metrics_filename, 'w', encoding="utf8") as metrics_for_gcs: + for metrics_step in running_metrics: + metrics_for_gcs.write(str(json.dumps(metrics_step))+'\n') + + metrics_for_gcs.close() + gcs_filename=os.path.join(config.metrics_dir, metrics_filename) + max_logging.log(f"Moving file {metrics_filename} to GCS...") + upload_blob(gcs_filename, metrics_filename) + max_logging.log(f"File {metrics_filename} moved successfully!") + running_metrics = [] # reset running_metrics to empty list + return running_metrics + +def write_config_raw_keys_for_gcs(raw_keys): + """Writes config raw keys to GCS""" + if not raw_keys["save_config_to_gcs"] or jax.process_index() != 0: + return + max_logging.log("Writing config to GCS...") + + raw_keys_dict = dict(raw_keys) + filename = "config.yml" + with open(filename, 'w', encoding="utf8") as config_for_gcs: + yaml.dump(raw_keys_dict, config_for_gcs) + config_for_gcs.close() + + gcs_filename=os.path.join(raw_keys["base_output_directory"], raw_keys["run_name"], filename) + max_logging.log(f"Moving file {filename} to GCS...") + upload_blob(gcs_filename, filename) + max_logging.log(f"File {filename} moved successfully!") + +def parse_gcs_bucket_and_prefix(destination_gcs_name): + path_parts = destination_gcs_name.replace("gs://", "").split("/") + bucket = path_parts.pop(0) + key = "/".join(path_parts) + return bucket, key + +def upload_blob(destination_gcs_name, source_file_name): + """Uploads a file to a GCS location""" + bucket_name, prefix_name = parse_gcs_bucket_and_prefix(destination_gcs_name) + storage_client = storage.Client() + bucket = storage_client.get_bucket(bucket_name) + blob = bucket.blob(prefix_name) + blob.upload_from_filename(source_file_name) + +def maybe_initialize_jax_distributed_system(raw_keys): + """ The best recipe to initialize the Jax Distributed System has varied over time. We keep a layer of + indirection in MaxText to avoid breaking the call sites unnecessarily. + + Currently jax.distributed.initialize() fully works as expected! + + For CPUs, we call jax.distributed.initialize() explicitly, with the specified arguments. + """ + if (raw_keys["enable_checkpointing"] and raw_keys["async_checkpointing"] + and raw_keys["compile_topology_num_slices"]==-1) or raw_keys["hardware"]=='gpu_multiprocess': + max_logging.log("Attempting to initialize the jax distributed system...") + jax.distributed.initialize() + max_logging.log("Jax distributed system initialized!") + elif is_gpu_backend(raw_keys): + max_logging.log("Attempting to initialize the jax distributed system for GPU backend...") + initialize_jax_for_gpu() + max_logging.log("Jax distributed system initialized on GPU!") + elif is_cpu_backend(raw_keys): + max_logging.log("Attempting to initialize the jax distributed system for CPU backend...") + initialize_jax_for_cpu() + max_logging.log("Jax distributed system initialized on CPUs!") + +def initialize_jax_for_gpu(): + """Jax distributed initialize for GPUs.""" + if os.environ.get("JAX_COORDINATOR_IP") is not None: + coordinator_ip = str(os.getenv("JAX_COORDINATOR_IP")) + coordinator_port = str(os.getenv("JAX_COORDINATOR_PORT")) + jax.distributed.initialize( + coordinator_address=f"{coordinator_ip}:{coordinator_port}", + num_processes=int(os.getenv("JAX_NUM_PROCESSES")), + process_id=int(os.getenv("PROCESS_ID")), + local_device_ids=int(os.getenv("LOCAL_DEVICE_ID")), + ) + max_logging.log(f"JAX global devices: {jax.devices()}") + +def initialize_jax_for_cpu(): + """Jax distributed initialize for CPUs. Includes retries until the coordinator is ready. + """ + coordinator_ip_address = get_coordinator_ip_address() + coordinator_address = coordinator_ip_address + ":1234" # JAX coordinator port used in XPK + # Env variables to be set in XPK or otherwise + job_index = int(os.environ.get("JOB_INDEX")) + job_completion_index = int(os.environ.get("JOB_COMPLETION_INDEX")) + processes_in_job = int(os.environ.get("PROCESSES_IN_JOB")) + pid = job_index * processes_in_job + job_completion_index + max_logging.log(f" Jax process id is {pid} ") + # Explicit initialize is needed only for CPUs + jax.distributed.initialize(coordinator_address=coordinator_address, + process_id=pid, + num_processes=int(os.environ.get("JAX_PROCESS_COUNT"))) + +def is_cpu_backend(raw_keys): + """Determine whether Maxtext is intended to run on a CPU backend.""" + return raw_keys["hardware"] == 'cpu' + +def is_gpu_backend(raw_keys): + """Determine whether Maxtext is intended to run on a GPU backend.""" + return raw_keys["hardware"] == 'gpu' + +def get_coordinator_ip_address(): + """Get coordinator IP Address with retries""" + coordinator_address = "" + if os.environ.get("JAX_COORDINATOR_ADDRESS") is not None: + coordinator_address = os.environ.get("JAX_COORDINATOR_ADDRESS") + coordinator_found = False + lookup_attempt = 1 + max_coordinator_lookups = 50 + while not coordinator_found and lookup_attempt <= max_coordinator_lookups: + try: + coordinator_ip_address = socket.gethostbyname(coordinator_address) + coordinator_found = True + except socket.gaierror: + max_logging.log( + f"Failed to recognize coordinator address {coordinator_address} on attempt {lookup_attempt}, retrying..." + ) + lookup_attempt += 1 + time.sleep(5) + max_logging.log(f"Coordinator IP address: {coordinator_ip_address}") + return coordinator_ip_address + +def fill_unspecified_mesh_axes(parallelism_vals, target_product, parallelism_type): + """Evaluates unspecified DCN/ICI parallelism values""" + if -1 in parallelism_vals: + assert parallelism_vals.count(-1) == 1, f"Found unspecified values (-1) for more than one {parallelism_type}\ + parallelism axis. At most one axis can be unspecified." + + determined_val = target_product/np.product(parallelism_vals)*-1 + + assert determined_val >= 1 and determined_val.is_integer, f"Unspecified value unable to be determined with the given\ + {parallelism_type} parallelism values" + + parallelism_vals[parallelism_vals.index(-1)] = int(determined_val) + + target_type = "slices" if parallelism_type == 'DCN' else "devices per slice" + + assert np.product(parallelism_vals) == target_product, f"Number of {target_type} {target_product} does not match\ + the product of the {parallelism_type} parallelism {np.product(parallelism_vals)}" + + return parallelism_vals + +def create_device_mesh(config, devices=None): + """Creates a device mesh with each slice in its own data parallel group. If there is only one slice, uses two replicas """ + if devices is None: + devices = jax.devices() + num_devices = len(devices) + num_slices = config.num_slices + num_devices_per_slice = num_devices//num_slices + + multi_slice_env = num_slices > 1 + + dcn_parallelism = [config.dcn_data_parallelism, config.dcn_fsdp_parallelism, + config.dcn_fsdp_transpose_parallelism, config.dcn_sequence_parallelism, + config.dcn_tensor_parallelism, config.dcn_autoregressive_parallelism] + ici_parallelism = [config.ici_data_parallelism, config.ici_fsdp_parallelism, + config.ici_fsdp_transpose_parallelism, config.ici_sequence_parallelism, + config.ici_tensor_parallelism, config.ici_autoregressive_parallelism] + + # Find possible unspecified parallelisms + ici_parallelism = fill_unspecified_mesh_axes(ici_parallelism, num_devices_per_slice, 'ICI') + + if multi_slice_env: + dcn_parallelism = fill_unspecified_mesh_axes(dcn_parallelism, num_slices, 'DCN') + mesh = mesh_utils.create_hybrid_device_mesh(ici_parallelism, dcn_parallelism, devices) + else: + mesh = mesh_utils.create_device_mesh(ici_parallelism, devices) + + max_logging.log(f"Num_devices: {num_devices}, shape {mesh.shape}") + + return mesh + +def unbox_logicallypartioned( + boxed_pytree): + """ Unboxes the flax.LogicallyPartitioned pieces + + Args: + boxed_pytree: a pytree that includes LogicallyPartitioned + leaves. + Returns: + a pytree where all all LogicallyPartitioned leaves have been unboxed. + """ + return jax.tree_util.tree_map(lambda x: x.unbox() if \ + isinstance(x, flax.linen.spmd.LogicallyPartitioned) \ + else x, boxed_pytree, \ + is_leaf=lambda k: isinstance(k, flax.linen.spmd.LogicallyPartitioned)) + +def init_decode_state(apply_fn, params): + """Init train state with null opt state for decode.""" + state = train_state.TrainState( + step=0, + apply_fn=apply_fn, + params=params, + tx=None, # type: ignore + opt_state={} + ) + return state + +def init_training_state(apply_fn, params, tx): + """Init train state with null opt state for decode.""" + state = train_state.TrainState.create( + apply_fn=apply_fn, + params=params, + tx=tx + ) + return state + +def init_initial_state(model, tx, config, is_training, key): + """ + We pass in "static" objects like model, tx, config as JAX compares them by + object hash, and instantiating them inside causes pjit top-level annotations + to fail to match as pytree prefixes if we re-instantiate. + + Args: model, tx, config, is_training, key + """ + input_shape = ( + config.global_batch_size_to_load, + config.max_target_length + ) + model_vars = model.init({'params': key, 'dropout': key, 'aqt': key}, + jnp.ones(input_shape, dtype=jnp.int32), + jnp.ones(input_shape, dtype=jnp.int32)) + if is_training: + return init_training_state(model.apply, model_vars['params'], tx) + return init_decode_state(model.apply, model_vars['params']) + +def load_decode_model_vars(model, config, rng, mesh): + state, _ = setup_decode_state(model, config, rng, mesh, None) + model_vars = {'params': state.params} + return model_vars + +def setup_decode_state(model, config, rng, mesh, checkpoint_manager): + is_training = False + state, state_mesh_annotations, _ = setup_initial_state(model, None, None, config, + rng, mesh, checkpoint_manager, + is_training) + return state, state_mesh_annotations + +def setup_training_state(model, data_iterator, tx, config, rng, mesh, checkpoint_manager): + is_training = True + return setup_initial_state(model, data_iterator, tx, config, rng, mesh, checkpoint_manager, is_training) + +def setup_initial_state(model, data_iterator, tx, config, rng, mesh, checkpoint_manager, is_training=True): + """ We initialize the model and optimizer state, and optionally load from a + checkpoint as necessary. + + Args: + model: the flax model to initialize + tx: the optax.GradientTransformation + config: config object + rng: jax.prng key + mesh: jax.devices() mesh + checkpoint_manager: an Orbax checkpointing.CheckpointManager object + is_training: True to initialize training state, False for decode state + + Returns: + state: the initialized train state + state_mesh_annotations: the mesh annotations for the train state + """ + + unboxed_abstract_state, state_mesh_annotations, state_mesh_shardings = get_abstract_state(model, tx, config, + rng, mesh, is_training) + + # Initialization + with nn_partitioning.axis_rules(config.logical_axis_rules): + restored, raw_params = checkpointing.load_state_if_possible(checkpoint_manager, + data_iterator, + config.load_parameters_path, + config.load_full_state_path, + unboxed_abstract_state, + config.enable_single_replica_ckpt_restoring, + config.dataset_type, + ) + + if restored: + if 'iter' in restored and restored['iter'] is not None: + data_iterator.local_iterator = restored['iter'] + state = restored['items'] + else: + init_state_partial = functools.partial(init_initial_state, model, tx, config, is_training) + state = jax.jit( + init_state_partial, + in_shardings=None, + out_shardings=state_mesh_shardings + )(rng) + if raw_params: # If we loaded a partial state, we need to merge it. + state = state.replace(params = raw_params) + + state = unbox_logicallypartioned(state) + return state, state_mesh_annotations, data_iterator + + +# Learning Rate Schedule +# ----------------------------------------------------------------------------- + +def create_learning_rate_schedule(config): + """Creates a warmup and cosine decay learning rate schedule: + We take inspiration from Llama2's learning rate (LR) schedule, see https://arxiv.org/pdf/2307.09288.pdf section 2.2 + Learning rate schedule has either two or three parts: + 1) Linear warmup from 0 to [learning_rate] over steps 0 to [learning_rate_schedule_steps * warmup_steps_fraction] + 2) Cosine from [learning_rate] to [learning_rate * cosine_learning_rate_final_fraction] until learning_rate_schedule_steps + 3) Constant learning rate of 0 from learning_rate_schedule_steps to steps. + The zero learning rate section can be used to more accurately measure the fully trained model's performance. + """ + def make_cos_schedule(init_lr, final_lr, len_steps): + def schedule(step): + pct = (step) / len_steps + a = 0.5 * (jnp.cos(jnp.pi*pct) + 1) + lr = init_lr * a + final_lr * (1 - a) + return lr + return schedule + + lr = config.learning_rate + cos_final_lr = lr * config.cosine_learning_rate_final_fraction + + warmup_steps = int(config.learning_rate_schedule_steps * config.warmup_steps_fraction) + cos_steps = config.learning_rate_schedule_steps - warmup_steps + constant_zero_steps = config.steps - config.learning_rate_schedule_steps + + warmup_schedule = optax.linear_schedule( + init_value=0.0, + end_value=lr, + transition_steps=warmup_steps + ) + cos_schedule = make_cos_schedule(lr, cos_final_lr, cos_steps) + constant_schedule = optax.constant_schedule(0.0) + + pieces = [warmup_schedule, cos_schedule] + boundaries=[ + warmup_steps, + warmup_steps + cos_steps, + ] + + if constant_zero_steps > 0: + pieces.append(constant_schedule) + boundaries.append(warmup_steps + cos_steps + constant_zero_steps) + + return optax.join_schedules(pieces, boundaries) + + +# Cross entropy implementation is taken from original T5X codebase: +# https://github.com/google-research/t5x/blob/ace831eea1e2742b4299cd1a9af7e4f302038351/t5x/losses.py#L25-L101 +@jax.custom_vjp +def cross_entropy_with_logits(logits: jnp.ndarray, targets: jnp.ndarray, + z_loss: float) -> Tuple[jnp.ndarray, jnp.ndarray]: + """Computes cross entropy loss with stable custom gradient. + Computes a stabilized-gradient version of: + -jnp.sum(targets * nn.log_softmax(logits), axis=-1) + If z_loss > 0, then an auxiliary loss equal to z_loss*log(z)^2 + will be added to the cross entropy loss (z = softmax normalization constant). + The two uses of z_loss are: + 1. To keep the logits from drifting too far from zero, which can cause + unacceptable roundoff errors in bfloat16. + 2. To encourage the logits to be normalized log-probabilities. + Args: + logits: [batch, length, num_classes] float array. + targets: categorical one-hot targets [batch, length, num_classes] float + array. + z_loss: coefficient for auxilliary z-loss loss term. + Returns: + tuple with the total loss and the z_loss, both + float arrays with shape [batch, length]. + """ + logits_sum = jax.scipy.special.logsumexp(logits, axis=-1, keepdims=True) + log_softmax = logits - logits_sum + loss = -jnp.sum(targets * log_softmax, axis=-1) + # Add auxilliary z-loss term. + log_z = jnp.squeeze(logits_sum, axis=-1) + total_z_loss = z_loss * jax.lax.square(log_z) + loss += total_z_loss + return loss, total_z_loss + + +def _cross_entropy_with_logits_fwd( + logits: jnp.ndarray, + targets: jnp.ndarray, + z_loss: float = 0.0 +) -> Tuple[Tuple[jnp.ndarray, jnp.ndarray], + Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray, jnp.ndarray, + jnp.ndarray, jnp.ndarray, jnp.ndarray]]: + """Forward-mode of `cross_entropy_with_logits`.""" + max_logit = logits.max(axis=-1, keepdims=True) + shifted = logits - max_logit + exp_shifted = jnp.exp(shifted) + sum_exp = jnp.sum(exp_shifted, axis=-1, keepdims=True) + log_softmax = shifted - jnp.log(sum_exp) + loss = -jnp.sum(targets * log_softmax, axis=-1) + # Add auxilliary z-loss term. + log_z = jnp.squeeze(jnp.log(sum_exp) + max_logit, axis=-1) + total_z_loss = z_loss * jax.lax.square(log_z) + loss += total_z_loss + return (loss, total_z_loss), (logits, targets, z_loss, exp_shifted, sum_exp, #pytype: disable=bad-return-type #jax-ndarray + log_softmax, log_z) + + +def _cross_entropy_with_logits_bwd( + res: Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray, jnp.ndarray, jnp.ndarray, + jnp.ndarray, jnp.ndarray], g: Tuple[jnp.ndarray, jnp.ndarray] +) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]: + """Backward-mode of `cross_entropy_with_logits`.""" + g = g[0] # Ignore z_loss component as that is only used for logging. + logits, targets, z_loss, exp_shifted, sum_exp, log_softmax, log_z = res + # z-loss term adds the (2 * z_loss * log_z) factor. + deriv = ( + jnp.expand_dims(1 + 2 * z_loss * log_z, -1) * exp_shifted / sum_exp - + targets) + g_logits = jnp.expand_dims(g, axis=-1) * deriv + g_targets = -jnp.expand_dims(g, axis=-1) * log_softmax + return (jnp.asarray(g_logits, + logits.dtype), jnp.asarray(g_targets, targets.dtype), + jnp.array(0.0)) # sets z-loss coeff gradient to 0 + +cross_entropy_with_logits.defvjp(_cross_entropy_with_logits_fwd, + _cross_entropy_with_logits_bwd) + +def get_abstract_state(model, tx, config, rng, mesh, is_training=True): + """ Get a shaped abstraction of the state (including optimizer)""" + init_state_partial = functools.partial(init_initial_state, model, tx, config, is_training) + + with nn_partitioning.axis_rules(config.logical_axis_rules): + abstract_state = jax.eval_shape(init_state_partial, rng) + + state_logical_annotations = nn.get_partition_spec(abstract_state) + + state_mesh_shardings = nn.logical_to_mesh_sharding(state_logical_annotations, mesh, + config.logical_axis_rules) + + abstract_sharded_state = jax.jit( + init_state_partial, + in_shardings=None, + out_shardings=state_mesh_shardings + ).eval_shape(rng) + + unboxed_abstract_sharded_state = unbox_logicallypartioned(abstract_sharded_state) + # Initialization + with mesh, nn_partitioning.axis_rules(config.logical_axis_rules): + state_mesh_annotations = nn.logical_to_mesh(state_logical_annotations) + return unboxed_abstract_sharded_state, state_mesh_annotations, state_mesh_shardings + +def get_kv_cache_annotations(model, config, rng, mesh): + """ Get a shaped abstraction of the state (including optimizer)""" + + def init_kv_cache(model, config): + input_shape = ( + config.global_batch_size_to_load, + config.max_prefill_predict_length + ) + + model_vars = model.init({'params': rng, 'dropout': rng, 'aqt': rng}, + jnp.ones(input_shape), + jnp.ones(input_shape), + model_mode=common_types.MODEL_MODE_PREFILL) + return model_vars['cache'] + + with nn_partitioning.axis_rules(config.logical_axis_rules): + init_kv_cache_partial = functools.partial(init_kv_cache, model, + config) + abstract_state = jax.eval_shape(init_kv_cache_partial) + state_logical_annotations = nn.get_partition_spec(abstract_state) + with mesh, nn_partitioning.axis_rules(config.logical_axis_rules): + state_mesh_annotations = nn.logical_to_mesh(state_logical_annotations) + return state_mesh_annotations + + +def print_pytree_shape(print_str, ptree): + print("\n") + print(print_str) + print(jax.tree_util.tree_map(lambda x : x.shape, ptree)) + +def print_model_vars(print_str, model_vars): + for k in model_vars: + print(f'{print_str} key{k}:') + print(f'\t {model_vars[k]}') diff --git a/maxtext-setup/maxtext/MaxText/maxengine.py b/maxtext-setup/maxtext/MaxText/maxengine.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c997e7a0e2595e2b3f7c4831121bbc88e2d1f4 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/maxengine.py @@ -0,0 +1,356 @@ +# Copyright 2024 Google LLC +# +# 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. + +''' Implementation of Engine API for MaxText ''' +import functools +from typing import Any, Optional, Tuple + +import flax +from flax import linen as nn +from flax.linen import partitioning as nn_partitioning +from flax import struct + +from layers import models, quantizations + +import jax +import jax.numpy as jnp +from jax.sharding import PartitionSpec as P + +import common_types +from jetstream.engine import engine_api +from jetstream.engine import tokenizer_pb2 + +import max_utils +import inference_utils + + +Prefix = Any +Params = Any + + + +@struct.dataclass +class DecodeState: + """The inputs into a generation step.""" + prefill_cache: jax.Array + generate_cache: jax.Array + generate_cache_index: int + generate_lengths: jax.Array + + +class MaxEngine(engine_api.Engine): + """The computational core of the generative model server. + + Engine defines an API that models must adhere to as they plug into the + JetStream efficient serving infrastructure. + """ + + def __init__(self, config): + self.config = config + self.rng = jax.random.PRNGKey(0) + + # Mesh definition + devices_array = max_utils.create_device_mesh(config) + self._mesh = jax.sharding.Mesh(devices_array, config.mesh_axes) + + # Model and Optimizer definition + quant = quantizations.configure_quantization(config) + self.model = models.Transformer(config, mesh = self._mesh, quant=quant) + self.replicated_sharding = jax.sharding.NamedSharding(self._mesh, P(None)) + + self.abstract_params = None + self.kv_cache_annotations = None + self.kv_cache_annotations_named = None + self.kv_cache_shardings = None + self.state_mesh_annotations = None + + def load_params(self, *args, **kwargs) -> Params: + ''' Load Parameters, typically from GCS ''' + # pylint: disable=unused-argument + state, self.state_mesh_annotations = max_utils.setup_decode_state( + self.model, self.config, self.rng, self._mesh, None + ) + self.abstract_params = jax.tree_map(lambda x: jax.ShapeDtypeStruct(shape=x.shape, dtype=x.dtype, sharding=x.sharding), + state.params) + self.kv_cache_annotations = max_utils.get_kv_cache_annotations(self.model, self.config, self.rng, self._mesh) + self.kv_cache_shardings = jax.tree_map(lambda x : jax.sharding.NamedSharding(self._mesh, x), self.kv_cache_annotations) + + if not self.model.quant: + params = {"params" : state.params} + self.abstract_params = jax.tree_map(lambda x: jax.ShapeDtypeStruct(shape=x.shape, dtype=x.dtype, sharding=x.sharding), + params) + return params + else: + self.model.quant.quant_mode = quantizations.get_quant_mode('convert') + + @jax.jit + def model_apply(_p, _rng): + return self.model.apply( + { + "params": _p, + "aqt" : {} + }, + jnp.ones( (1, self.config.max_prefill_predict_length), dtype=jnp.int32), + jnp.ones( (1, self.config.max_prefill_predict_length), dtype=jnp.int32), + decoder_segment_ids=jnp.zeros((1, self.config.max_prefill_predict_length), dtype=jnp.int32), + enable_dropout=False, + model_mode=common_types.MODEL_MODE_PREFILL, + rngs={'params': _rng}, + mutable=True + ) + + _, new_vars = model_apply(state.params, self.rng) + + params = {} + params['aqt'] = new_vars['aqt'] + # Remove param values which have corresponding qtensors in aqt to save memory. + params['params'] = quantizations.remove_quantized_params(state.params, new_vars['aqt']) + + self.abstract_params = jax.tree_map(lambda x: jax.ShapeDtypeStruct(shape=x.shape, dtype=x.dtype, sharding=x.sharding), + params) + + self.model.quant.quant_mode = quantizations.get_quant_mode('serve') + return params + + @functools.partial(jax.jit, static_argnums=(0,)) + def prefill( + self, + *, + params: Params, + existing_prefix: Optional[jax.Array] = None, + padded_tokens: jax.Array, + true_length: int, + ) -> Prefix: + """Computes a kv-cache for a new generate request. + + Args: + params: Scalar multiplier. + existing_prefix: If provided, represents a prefix that has already been + processed by the underlying model. + padded_tokens: Logically appended tokens to any existing prefix, this is + what we compute prefill on. + true_length: The real length of the tokens, pre-pad. + Returns: + kv_cache: For the resulting text. + """ + if existing_prefix: + raise ValueError("We don't know what to do with existing_prefix") + + input_tokens = jnp.expand_dims(padded_tokens, 0) # [BATCH, SEQUENCE] + positions = jnp.expand_dims(jnp.arange(0, input_tokens.shape[1]), 0) + + zero_to_n = jnp.arange(0, padded_tokens.shape[0]) + ones_to_keep = zero_to_n < true_length + one_d_output = ones_to_keep * common_types.DECODING_ACTIVE_SEQUENCE_INDICATOR + sequence_indicator = jnp.expand_dims(one_d_output, 0) + + with self._mesh, nn_partitioning.axis_rules(self.config.logical_axis_rules): + flat_logits, new_vars = self.model.apply( + params, + input_tokens, + positions, + decoder_segment_ids=sequence_indicator, + enable_dropout=False, + model_mode=common_types.MODEL_MODE_PREFILL, + rngs={'params': self.rng}, + mutable=["cache"] + ) + + next_pos = jnp.full((1,1), true_length, dtype = jnp.int32) + generated_tokens = jnp.zeros((1,1), dtype = jnp.int32) + selected_logits = jax.lax.dynamic_slice(flat_logits, (0, true_length-1,0), + (flat_logits.shape[0], 1, flat_logits.shape[2])) + selected_logits = jax.lax.with_sharding_constraint(selected_logits, self.replicated_sharding) + return {"logits" : selected_logits, "cache" : new_vars['cache'], + "next_pos" : next_pos, "generated_tokens" : generated_tokens} + + @functools.partial(jax.jit, static_argnums=(0,), donate_argnums=(2,)) + def generate( + self, params: Params, decode_state: DecodeState + ) -> Tuple[DecodeState, engine_api.ResultTokens]: + '''Run one generate step''' + previous_logits = decode_state['logits'] + + new_token = inference_utils.sampling(previous_logits, self.rng, self.config.decode_sampling_strategy, + topk=self.config.decode_sampling_top_k, + nucleus_topp=self.config.decode_sampling_nucleus_p, + temperature=self.config.decode_sampling_temperature) + + with self._mesh, nn_partitioning.axis_rules(self.config.logical_axis_rules): + out_logits, new_vars = self.model.apply( + params | { 'cache': decode_state['cache']}, + new_token, + decode_state['next_pos'], + enable_dropout=False, + model_mode=common_types.MODEL_MODE_AUTOREGRESSIVE, + rngs={'params': self.rng}, + mutable=['cache'] + ) + + all_valid = jnp.ones(new_token.shape, dtype=jnp.int8) + + result = engine_api.ResultTokens( + data=jnp.concatenate((new_token, all_valid, decode_state["generated_tokens"]), axis=1), + # Tokens are shape [batch, speculations], so when we concatenate + # tokens, validity and length along their index 1 dimension then they + # occupy 0:speculations. + tokens_idx=(0, 1), + # Validity occupies the same amount of space, but next in line. + valid_idx=(1, 2), + # And lengths is rank 1. + length_idx=(2, 3), + samples_per_slot=1, + ) + + out_logits = jax.lax.with_sharding_constraint(out_logits, self.replicated_sharding) + new_cache = jax.lax.with_sharding_constraint(new_vars["cache"], self.kv_cache_shardings) + + return {"logits" : out_logits, "cache" : new_cache, + "next_pos" : decode_state["next_pos"]+1, "generated_tokens" : decode_state["generated_tokens"]+1}, result + + @functools.partial(jax.jit, static_argnums=(0,), donate_argnums=(1, 2,)) + def insert( + self, + prefix: Prefix, + decode_state: DecodeState, + slot: int, + ) -> DecodeState: + ''' Insert into KV cache ''' + unboxed_prefix = max_utils.unbox_logicallypartioned(prefix) + + def copy(path, partial_cache, full_cache, annotations): + path_key = path[-1].key + if path_key in ['cache_ar_index', 'cached_ar_key', 'cached_ar_value', 'cached_ar_key_scale', 'cached_ar_value_scale']: + return full_cache # we don't even zero these out because we can mask them out. + + batch_idx = annotations.index("cache_batch") if "cache_batch" in annotations else -1 + if batch_idx < 0: + raise ValueError(f"Batch index {batch_idx=} shouldn't be less than zero for {path_key}, got {annotations=}") + + if path_key == 'cache_ar_segment_id': + ### goal: zero this out in case there is existing data + s = list(full_cache.shape) + s[batch_idx] = 1 + zeros = jnp.zeros(tuple(s), dtype=jnp.int32) + return jax.lax.dynamic_update_index_in_dim(full_cache, zeros, slot, batch_idx) + elif path_key == 'cache_prefill_segment_id': + s = list(full_cache.shape) + s[batch_idx] = 1 + zeros = jnp.zeros(tuple(s), dtype=jnp.int32) + ## zero out in case prefill cache is too small to cover + full_cache = jax.lax.dynamic_update_index_in_dim(full_cache, zeros, slot, batch_idx) + ## copy prefill cachce + full_cache = jax.lax.dynamic_update_index_in_dim(full_cache, partial_cache, slot, batch_idx) + return full_cache + elif path_key in ['cached_prefill_key', 'cached_prefill_value', + 'cached_prefill_key_scale', 'cached_prefill_value_scale']: + return jax.lax.dynamic_update_index_in_dim(full_cache, partial_cache, slot, batch_idx) + else: + raise ValueError(f"We don't have a strategy for inserting {path_key}") + + inserted_cache = jax.tree_util.tree_map_with_path(copy, unboxed_prefix['cache'], decode_state['cache'], + self.kv_cache_annotations_named) + inserted_logits = jax.lax.dynamic_update_index_in_dim(decode_state['logits'], unboxed_prefix['logits'], slot, 0) + inserted_next_pos = jax.lax.dynamic_update_index_in_dim(decode_state['next_pos'], unboxed_prefix['next_pos'], slot, 0) + inserted_generated_tokens = jax.lax.dynamic_update_index_in_dim(decode_state['generated_tokens'], + unboxed_prefix['generated_tokens'], slot, 0) + + inserted_logits = jax.lax.with_sharding_constraint(inserted_logits, self.replicated_sharding) + inserted_generated_tokens = jax.lax.with_sharding_constraint(inserted_generated_tokens, self.replicated_sharding) + inserted_next_pos = jax.lax.with_sharding_constraint(inserted_next_pos, self.replicated_sharding) + inserted_cache = jax.lax.with_sharding_constraint(inserted_cache, self.kv_cache_shardings) + + return {'logits' : inserted_logits, 'cache' : inserted_cache, + 'next_pos' : inserted_next_pos, 'generated_tokens' : inserted_generated_tokens } + + def get_prefix_destination_sharding(self) -> Any: + return jax.sharding.NamedSharding( + mesh=self.mesh, spec=jax.sharding.PartitionSpec() + ) + + def get_tokenizer(self) -> tokenizer_pb2.TokenizerParameters: + """Return a protobuf of tokenizer info, callable from Py or C++.""" + return tokenizer_pb2.TokenizerParameters(path=self.config.tokenizer_path, extra_ids=0) + + def init_decode_state(self, *args, **kwargs) -> DecodeState: + """Initialises any state which a generation step transforms.""" + # pylint: disable=unused-argument + def init(abstract_params): + x = jnp.ones( (int(self.config.per_device_batch_size * jax.device_count()), self.config.max_prefill_predict_length), + dtype=jnp.int32) + _, cache = self.model.apply( + abstract_params, + x, + x, + decoder_segment_ids=jnp.zeros(x.shape, dtype=jnp.int32) + common_types.DECODING_ACTIVE_SEQUENCE_INDICATOR, + enable_dropout=False, + model_mode=common_types.MODEL_MODE_PREFILL, + rngs={'params': self.rng}, + mutable=["cache"] + ) + + next_pos = jnp.zeros((int(self.config.per_device_batch_size * jax.device_count()), 1), dtype=jnp.int32) + generated_tokens = jnp.zeros((int(self.config.per_device_batch_size * jax.device_count()), 1), dtype=jnp.int32) + return {"logits" : jnp.zeros((int(self.config.per_device_batch_size * jax.device_count()), 1, self.config.vocab_size)), + "cache" : cache["cache"], + "next_pos" : next_pos, + "generated_tokens" : generated_tokens + } + + with nn_partitioning.axis_rules(self.config.logical_axis_rules): + abstract_outputs = jax.eval_shape(init, self.abstract_params) + logical_annotations = nn.get_partition_spec(abstract_outputs) + + with self._mesh, nn_partitioning.axis_rules(self.config.logical_axis_rules): + mesh_annotations = nn.logical_to_mesh(logical_annotations) + + shardings = jax.tree_map(lambda mesh_annotation : jax.sharding.NamedSharding(self._mesh, mesh_annotation), + mesh_annotations) + + @functools.partial(jax.jit, out_shardings = shardings) + def initialize(): + return jax.tree_map( lambda x : jnp.zeros(x.shape, x.dtype), abstract_outputs) + + cache = initialize()['cache'] + + def is_lp(k): + return isinstance(k, flax.linen.spmd.LogicallyPartitioned) + self.kv_cache_annotations_named = jax.tree_util.tree_map(lambda x : tuple(x.names), cache, is_leaf=is_lp) + del cache + zeroed = max_utils.unbox_logicallypartioned(initialize()) + return zeroed + + @property + def max_concurrent_decodes(self) -> int: + """Free slots.""" + return int(self.config.per_device_batch_size * jax.device_count()) + + @property + def max_prefill_length(self) -> int: + """Maximum prefill length.""" + return int(self.config.max_prefill_predict_length) + + @property + def samples_per_slot(self) -> int: + """Number of samples per slot.""" + return 1 + + @property + def mesh(self) -> jax.sharding.Mesh: + return self._mesh + + @property + def colocated_cpus(self) -> None: + """CPU devices colocated with the engine's accelerators.""" + raise NotImplementedError diff --git a/maxtext-setup/maxtext/MaxText/maxengine_config.py b/maxtext-setup/maxtext/MaxText/maxengine_config.py new file mode 100644 index 0000000000000000000000000000000000000000..da96c06f95ab070080431eb533701e6218197e5a --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/maxengine_config.py @@ -0,0 +1,48 @@ +# Copyright 2024 Google LLC +# +# 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. + +'''Configure MaxText For JetStream''' +import functools + +import jax +from typing import Any, Type + +from jetstream.core import config_lib +from jetstream.engine import engine_api +import maxengine + +def create_maxengine(devices: config_lib.Devices, config: Any) -> engine_api.Engine: + del devices + return maxengine.MaxEngine(config) + + +def get_server_config(config_str: str, config: Any) -> Type[config_lib.ServerConfig]: + ''' Gets the Server Config Required by JetStream ''' + match config_str: + case 'MaxtextInterleavedServer': + server_config = config_lib.ServerConfig( + prefill_slices = (), + generate_slices = (), + interleaved_slices = ('tpu='+str(jax.device_count()),), + prefill_engine_create_fns = (), + generate_engine_create_fns = (), + interleaved_engine_create_fns = (functools.partial( + create_maxengine, + config=config + ), + ) + ) + case _: + raise NotImplementedError + return server_config diff --git a/maxtext-setup/maxtext/MaxText/maxengine_server.py b/maxtext-setup/maxtext/MaxText/maxengine_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf46c8a5d33709481b17805c5c03367551e4329 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/maxengine_server.py @@ -0,0 +1,57 @@ +# Copyright 2024 Google LLC +# +# 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. + +"""Runs a server with maxtext.""" + +import jax +import os +import sys +import pyconfig + +import maxengine_config +from jetstream.core import server_lib + +# _PORT = flags.DEFINE_integer('port', 9000, 'port to listen on') +# _THREADS = flags.DEFINE_integer( +# 'threads', 64, 'number of worker threads in thread pool' +# ) +# _CONFIG = flags.DEFINE_string( +# 'config', +# 'MaxtextInterleavedServer', +# 'available servers', +# ) + + +def main(config): + # No devices for local cpu test. A None for prefill and a None for generate. + devices = server_lib.get_devices() + server_config = maxengine_config.get_server_config('MaxtextInterleavedServer', config) + # We separate credential from run so that we can unit test it with + # local credentials. + # TODO: Add grpc credentials for OSS. + jetstream_server = server_lib.run( + threads=256, + port=9000, + config=server_config, + devices=devices, + ) + jetstream_server.wait_for_termination() + + +if __name__ == '__main__': + jax.config.update('jax_default_prng_impl', 'unsafe_rbg') + os.environ["TF_CPP_MIN_LOG_LEVEL"] = "0" + pyconfig.initialize(sys.argv) + cfg = pyconfig.config + main(cfg) diff --git a/maxtext-setup/maxtext/MaxText/maxtext_utils.py b/maxtext-setup/maxtext/MaxText/maxtext_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0013f215ba934acfb5a11c86e2bb58446363a7e1 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/maxtext_utils.py @@ -0,0 +1,126 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=bare-except, consider-using-generator +"""Utils that are only interesting to MaxText. """ + +import jax +from jax.sharding import PartitionSpec as P +from jax.experimental.serialize_executable import deserialize_and_load + + +import pickle +import functools +from input_pipeline import input_pipeline_interface + + + +def get_functional_train_with_signature(train_step, mesh, state_mesh_annotations, model, config): + """ Get the shardings (both state and data) for train_step """ + functional_train = get_functional_train_step(train_step, model, config) + functional_train.__name__ = "train_step" + data_pspec = P(*config.data_sharding) + state_mesh_shardings = jax.tree_map( + lambda p: jax.sharding.NamedSharding(mesh, p), state_mesh_annotations) + data_sharding = jax.tree_map( + lambda p: jax.sharding.NamedSharding(mesh, p), data_pspec) + in_shardings = (state_mesh_shardings, data_sharding, None) # State, batch, rng + out_shardings = (state_mesh_shardings, None) # State, metrics + static_argnums = () # We partial out the static argnums of model and config + donate_argnums = 0 # This is the index of the state - we allow the compiler to make use of this memory. + return functional_train, in_shardings, out_shardings, static_argnums, donate_argnums + +def get_functional_train_step(train_step, model, config): + return functools.partial(train_step, model, config) + +def get_functional_eval_with_signature(eval_step, mesh, state_mesh_annotations, model, config): + """ Get the shardings (both state and data) for eval_step """ + functional_eval = get_functional_eval_step(eval_step, model, config) + functional_eval.__name__ = "eval_step" + data_pspec = P(*config.data_sharding) + state_mesh_shardings = jax.tree_map( + lambda p: jax.sharding.NamedSharding(mesh, p), state_mesh_annotations) + data_sharding = jax.tree_map( + lambda p: jax.sharding.NamedSharding(mesh, p), data_pspec) + in_shardings = (state_mesh_shardings, data_sharding, None) # State, batch, rng + out_shardings = None # metrics + static_argnums = () # We partial out the static argnums of model, config + donate_argnums = () # state will be kept instead of being donated in eval_step + return functional_eval, in_shardings, out_shardings, static_argnums, donate_argnums + +def get_functional_eval_step(eval_step, model, config): + return functools.partial(eval_step, model, config) + +def load_compiled(config, partial_train, state): + """ # Loading a serialized compiled train step function.""" + # Currently partial_train and state are needed to reconstruct + # input/output shapes to construct the in_trees and out_trees for load API + # Parker is working on a serializing these + def load_serialized_compiled(save_name): + with open(save_name, "rb") as f: + serialized_compiled = pickle.load(f) + return serialized_compiled + + def get_train_input_output_trees(func, input_args, input_kwargs): + _, in_tree_recreated = jax.tree_util.tree_flatten((input_args, input_kwargs)) + out_shaped = jax.eval_shape(func, *input_args, **input_kwargs) + _, out_tree_recreated = jax.tree_util.tree_flatten(out_shaped) + return in_tree_recreated, out_tree_recreated + + serialized_compiled = load_serialized_compiled(config.compiled_trainstep_file) + shaped_batch = input_pipeline_interface.get_shaped_batch(config) + example_rng = jax.random.PRNGKey(0) + shaped_input_args = (state, shaped_batch, example_rng) + shaped_input_kwargs = {} + in_tree, out_tree = get_train_input_output_trees(partial_train, shaped_input_args, shaped_input_kwargs) + p_train_step = deserialize_and_load(serialized_compiled, in_tree, out_tree) + return p_train_step + +# https://arxiv.org/pdf/2204.02311.pdf Appendix B +def calculate_tflops_training_per_device(num_model_parameters, config, log=True): + """ Calculate training TFLOP""" + learnable_weight_tflops = 6 * num_model_parameters * config.max_target_length * config.per_device_batch_size \ + / 10**12 + noncasual_attention_flops = 12 * config.num_query_heads * config.num_decoder_layers * config.head_dim \ + * config.max_target_length**2 * config.per_device_batch_size / 10**12 + causal_attention_tflops = noncasual_attention_flops / 2 # due to causality in attention + total_tflops = learnable_weight_tflops + causal_attention_tflops + + if log: + print('Per train step:\n', + f'Total TFLOPs: {total_tflops:.2f} \n', + f'split as {100 * learnable_weight_tflops/total_tflops:.2f}% learnable weight flops', + f'and {100 * causal_attention_tflops/total_tflops:.2f}% attention flops') + return total_tflops, learnable_weight_tflops, causal_attention_tflops + +# https://arxiv.org/pdf/2204.02311.pdf Appendix B +def calculate_tflops_prefill(num_model_parameters, prefill_length, config, log=True): + """ Calculate training TFLOP""" + learnable_weight_tflops = 2 * num_model_parameters * prefill_length \ + / 10**12 + noncasual_attention_flops = 4 * config.num_query_heads * config.num_decoder_layers * config.head_dim \ + * prefill_length**2 * config.per_device_batch_size / 10**12 + causal_attention_tflops = noncasual_attention_flops / 2 # due to causality in attention + total_tflops = learnable_weight_tflops + causal_attention_tflops + + if log: + print('Per prefill step: \n', + f'\tTotal TFLOPs: {total_tflops:.2f} \n', + f'\t\tLearnable weight TFLOPs: {learnable_weight_tflops} ', + f'({100 * learnable_weight_tflops/total_tflops:.2f})% of Total\n', + f'\t\tCausal attention TFLOPs: {causal_attention_tflops} ', + f'({100 * causal_attention_tflops/total_tflops:.2f})% of Total') + return total_tflops, learnable_weight_tflops, causal_attention_tflops diff --git a/maxtext-setup/maxtext/MaxText/multihost_dataloading.py b/maxtext-setup/maxtext/MaxText/multihost_dataloading.py new file mode 100644 index 0000000000000000000000000000000000000000..8c9088961cb07c85f0e538a24715985cb74b5708 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/multihost_dataloading.py @@ -0,0 +1,121 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=unused-import +"""SPMD Multihost Dataloading Utilities. + +Adapted from Sholto's: +https://github.com/sholtodouglas/multihost_dataloading +""" +from functools import lru_cache, partial # pylint: disable=g-importing-member +from typing import Callable, Any, Union +from collections.abc import Iterator +import tensorflow as tf # pylint: disable=g-import-not-at-top +import time +import numpy as np + +import jax +import jax.tree_util as jtu +from jax.sharding import PartitionSpec +from jax.sharding import NamedSharding +from jax.sharding import Mesh +import grain.python as grain + +import max_logging + +def _build_global_shape_and_sharding( + local_shape: tuple[int, ...], global_mesh: Mesh +) -> tuple[tuple[int, ...], NamedSharding]: + sharding = NamedSharding(global_mesh, PartitionSpec(global_mesh.axis_names)) + + global_shape = (jax.process_count() * local_shape[0],) + local_shape[1:] + + return global_shape, sharding + + +def _form_global_array(path, array: np.ndarray, global_mesh: Mesh) -> jax.Array: + """ Put local sharded array into local devices + """ + global_shape, sharding = _build_global_shape_and_sharding(np.shape(array), global_mesh) + + try: + local_device_arrays = np.split(array, len(global_mesh.local_devices), axis=0) + except ValueError as array_split_error: + raise ValueError( + f"Unable to put to devices shape {array.shape} with " + f"local device count {len(global_mesh.local_devices)} " + f"at {jtu.keystr(path)}" + ) from array_split_error + + local_device_buffers = jax.device_put(local_device_arrays, global_mesh.local_devices) + return jax.make_array_from_single_device_arrays(global_shape, sharding, local_device_buffers) + + + +def get_next_batch_sharded( + local_iterator: Iterator, global_mesh: Mesh +) -> jax.Array: + """Splits the host loaded data equally over all devices.""" + + SLEEP_TIME = 10 + MAX_DATA_LOAD_ATTEMPTS = 30 + + data_load_attempts = 0 + loaded_data_success = False + while not loaded_data_success and data_load_attempts < MAX_DATA_LOAD_ATTEMPTS: + data_load_attempts += 1 + try: + local_data = next(local_iterator) + loaded_data_success = True + except tf.errors.FailedPreconditionError: + max_logging.log("Failed to get next data batch, retrying") + time.sleep(SLEEP_TIME) + + # Try one last time, if this fails we will see the full stack trace. + if not loaded_data_success: + local_data = next(local_iterator) + + input_gdas = jtu.tree_map_with_path(partial(_form_global_array, global_mesh = global_mesh), local_data) + + return input_gdas + + +class MultiHostDataLoadIterator: + """fold get_next_batch_sharded into a iterator class""" + def __init__(self, dataloader: Union[tf.data.Dataset, grain.DataLoader], global_mesh: Mesh): + self.global_mesh = global_mesh + self.dataloader = dataloader + if isinstance(self.dataloader, tf.data.Dataset): + self.local_iterator = self.dataloader.as_numpy_iterator() + elif isinstance(self.dataloader, grain.DataLoader): + self.local_iterator = iter(self.dataloader) + else: + raise ValueError("Type error: dataloader should be either tf.data.Dataset or grain.DataLoader.") + + def reset(self): + if isinstance(self.dataloader, tf.data.Dataset): + self.local_iterator = self.dataloader.as_numpy_iterator() + elif isinstance(self.dataloader, grain.DataLoader): + self.local_iterator = iter(self.dataloader) + else: + raise ValueError("Type error: dataloader should be either tf.data.Dataset or grain.DataLoader.") + + def __iter__(self): + self.reset() + return self + + def __next__(self): + return get_next_batch_sharded(self.local_iterator, self.global_mesh) diff --git a/maxtext-setup/maxtext/MaxText/optimizers.py b/maxtext-setup/maxtext/MaxText/optimizers.py new file mode 100644 index 0000000000000000000000000000000000000000..e2a23abda58d6c7867b639bb4307a50f6aac3170 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/optimizers.py @@ -0,0 +1,149 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=bare-except, consider-using-generator, ungrouped-imports +"""Utils that are only interesting to MaxText. """ + +import jax + + +import optax +import jax.numpy as jnp + + +def get_optimizer(config, learning_rate_schedule): + """create optimizer""" + if config.opt_type == "adamw": + # Create AdamW Optimizer following Llama2's training details, see https://arxiv.org/pdf/2307.09288.pdf section 2.2 + return optax.adamw( + learning_rate_schedule, + b1=config.adam_b1, + b2=config.adam_b2, + eps=config.adam_eps, + eps_root=config.adam_eps_root, + weight_decay=config.adam_weight_decay, + ) + elif config.opt_type == "adam_pax": + return adam_pax( + learning_rate_schedule, + beta1=config.adam_b1, + beta2=config.adam_b2, + epsilon=config.adam_eps, + epsilon_root=config.adam_eps_root, + weight_decay=config.adam_weight_decay, + ) + else: + raise ValueError(f"{config.opt_type=} is not a supported.") + +def adam_pax( + learning_rate_fn: optax.Schedule, + beta1: float, + beta2: float, + epsilon: float, + epsilon_root: float, + weight_decay: float, + ) -> optax.GradientTransformation: + """Standard Adam optimizer that supports weight decay. + + Follows the implemenation in pax/praxis sharded_adam + https://github.com/google/praxis/blob/545e00ab126b823265d70c715950d39333484f38/praxis/optimizers.py#L621 + + Args: + learning_rate_fn: a callable that given the current training step, returns + the learning rate to apply. + beta1: decay rate to track the first moment. + beta2: decay rate to track the second moment. + epsilon: Small constant applied to the denominator outside of the square + root to avoid dividing by zero when rescaling. + epsilon_root: Small constant applied to the denominator inside of the square + root to avoid dividing by zero when rescaling. + weight_decay: If > 0, weight decay to apply. + + Returns: + A `optax.GradientTransformation`. + """ + + def init_fn(params): + mu = jax.tree_util.tree_map( # First moment + jnp.zeros_like, params) + nu = jax.tree_util.tree_map(jnp.zeros_like, params) # Second moment + return optax.ScaleByAdamState(count=jnp.zeros([], jnp.int32), mu=mu, nu=nu) + + def bias_corrected_decay(step: jnp.int32, decay: float): + """Incorporates bias correction into decay. + + Please see section 7.1 in https://arxiv.org/pdf/1804.04235.pdf for the + derivation of the formulas below. With bias-corrected decay, we can simply + do + + m_{t} = decay1 * m_{t-1} + (1 - decay1) * g + v_{t} = decay2 * v_{t-1} + (1 - decay2) * g ^ 2 + + without further bias correction. + + Args: + step: current step, 0-based. + decay: the raw decay. As t -> infinity, bias corrected decay converges to + this value. + + Returns: + Bias corrected decay. + """ + t = step.astype(jnp.float32) + 1. + return decay * (1. - jnp.power(decay, t - 1.)) / (1. - jnp.power(decay, t)) + + def update_fn(updates, state, params=None): + # Sanitize updates just in case. + if weight_decay > 0: + assert params is not None + count = state.count + + class _slot_opt_state: + def __init__(self, mu, nu): + self.mu = mu + self.nu = nu + + def _update_momentum(update, mu, nu): + # The conversion to the data type of the update ensures that bfloat16 remains + # bfloat16 in the optimizer state. This conversion has to be done after + # `bias_corrected_dacay` is calculated as calculating `jnp.power(decay, t)` in low + # precision can result in it being rounded to 1 and subsequently a + # "division by zero" error. + beta1_decay = bias_corrected_decay(count, beta1).astype(update) + beta2_decay = bias_corrected_decay(count, beta2).astype(update) + mu = (1.0 - beta1_decay) * update + beta1_decay * mu + nu = (1.0 - beta2_decay) * (update**2) + beta2_decay * nu + return _slot_opt_state(mu=mu, nu=nu) + + updated_moments = jax.tree_map(_update_momentum, updates, state.mu, state.nu) + + mu = jax.tree_map(lambda x: x.mu, updated_moments) + nu = jax.tree_map(lambda x: x.nu, updated_moments) + + updates = jax.tree_map( + lambda mu, nu: mu / (jnp.sqrt(nu + epsilon_root) + epsilon), mu, nu) + + if weight_decay > 0: + updates = jax.tree_map(lambda x, v: x + weight_decay * v, updates, params) + + step_size = -1.0 * learning_rate_fn(count) + # Finally, fold in step size. + updates = jax.tree_map(lambda x: step_size * x, updates) + + updated_states = optax.ScaleByAdamState(count=count + 1, mu=mu, nu=nu) + return updates, updated_states + + return optax.GradientTransformation(init_fn, update_fn) diff --git a/maxtext-setup/maxtext/MaxText/pyconfig.py b/maxtext-setup/maxtext/MaxText/pyconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..46f7d328239237b77e7da2bccb4db3dd9f2e20a8 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/pyconfig.py @@ -0,0 +1,390 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=missing-module-docstring, bare-except, consider-using-generator +from collections import OrderedDict +import math +import os +import sys +from typing import Any, Union + +import jax +from jax.experimental.compilation_cache import compilation_cache +import accelerator_to_spec_map +import max_logging +import max_utils +import yaml + +# pylint: disable=line-too-long + +_MAX_PREFIX = "M_" + +# YAML attribute to specify inheritance. +_BASE_CONFIG_ATTR = "base_config" + +def yaml_key_to_env_key(s: str) -> str: + return _MAX_PREFIX + s.upper() + +def string_to_bool(s: str) -> bool: + if s.lower() == "true": + return True + if s.lower() == "false": + return False + raise ValueError(f"Can't convert {s} to bool") + +_yaml_types_to_parser = {str : str, int : int, float : float, bool : string_to_bool} + +def validate_attention_type(s: str) -> None: + valid_attention_types = ('autoselected', 'dot_product', 'flash', 'cudnn_flash_te') + if s not in valid_attention_types: # currently supported attention + raise ValueError( + "Invalid attention type was passed. Valid options ", valid_attention_types + ) + +def validate_keys(keys): + validate_attention_type(keys['attention']) + + assert ((keys["load_parameters_path"]=="" and keys["load_full_state_path"]=="") or + keys["enable_checkpointing"]), "You must set enable_checkpointing to load a checkpoint" + assert keys["load_parameters_path"]=="" or keys["load_full_state_path"]=="",\ + "At most one of `load_parameters_path` or `load_full_state_path` should be set" + +def validate_model_name(s: str) -> bool: + # currently supported models + valid_model_names = ('default', 'llama2-7b', 'llama2-13b', 'llama2-70b', 'mistral-7b', + 'mixtral-8x7b', 'gemma-7b','gemma-2b', + 'gpt3-175b', 'gpt3-22b', 'gpt3-6b', 'gpt3-52k') + if s not in valid_model_names: + raise ValueError( + "Invalid model name was passed. Valid options ", valid_model_names + ) + +def validate_no_keys_overwritten_twice(keys1: list[str], keys2: list[str]): + overwritten_keys = [k for k in keys1 if k in keys2] + if overwritten_keys: + raise ValueError( + f"Keys {overwritten_keys} are overwritten from both the model" + " and the environment/command line. This isn't allowed.") + +_config = None +config = None + +def print_system_information(): + max_logging.log(f"System Information: Jax Version: {jax.__version__}") + max_logging.log(f"System Information: Jaxlib Version: {jax.lib.__version__}") + max_logging.log(f"System Information: Jax Backend: {jax.lib.xla_bridge.get_backend().platform_version}") + +def _lists_to_tuples(l: list[Any]) -> Union[tuple[Any],list[Any]]: + return tuple(_lists_to_tuples(x) for x in l) if isinstance(l, list) else l + +class _HyperParameters(): + # pylint: disable=missing-class-docstring + def _validate_env_variables(self, raw_data_from_yaml: dict[str, Any]): + for environment_var in os.environ: + if environment_var[:len(_MAX_PREFIX)] == _MAX_PREFIX: + proposed_key = environment_var[len(_MAX_PREFIX):].lower() + if proposed_key not in raw_data_from_yaml: + raise ValueError(f"We received env `{environment_var}` but it doesn't match a key, so it is assumed a mistake.") + if not environment_var[len(_MAX_PREFIX):].isupper(): + raise ValueError(f"We received env `{environment_var}` but it isn't all uppercase.") + + def _load_kwargs(self, argv: list[str], **kwargs): + args_dict = dict(a.split("=", 1) for a in argv[2:]) + args_dict.update(kwargs) + return args_dict + + def _update_from_env_and_command_line(self, raw_keys, raw_data_from_yaml, argv, **kwargs) -> list[str]: + ''' Update model config from environment and command line + ''' + raw_data_from_cmd_line = self._load_kwargs(argv, **kwargs) + updated_keys = [] + + for k in raw_data_from_cmd_line: + if k not in raw_data_from_yaml: + raise ValueError( + f"Key {k} was passed at the command line but isn't in config." + ) + + for k in raw_data_from_yaml: + if k in raw_data_from_cmd_line and yaml_key_to_env_key(k) in os.environ: + raise ValueError( + f"You are passing overrides by both CLI and ENV for `{k}`. This isn't allowed.") + + if not k in raw_data_from_cmd_line and not yaml_key_to_env_key(k) in os.environ: + raw_keys[k] = raw_data_from_yaml[k] + continue + + updated_keys.append(k) + if k in raw_data_from_cmd_line: + new_proposal = raw_data_from_cmd_line[k] + else: + new_proposal = os.environ.get(yaml_key_to_env_key(k)) + + if (not isinstance(new_proposal, type(raw_data_from_yaml[k]))) and \ + (type(raw_data_from_yaml[k]) not in _yaml_types_to_parser): + raise ValueError( + f"For key '{k}', type {type(raw_data_from_yaml[k])} not in {_yaml_types_to_parser.keys()}, can't pass" + " at the CLI or ENV" + ) + + if isinstance(new_proposal, type(raw_data_from_yaml[k])): + raw_keys[k] = new_proposal # take the raw data, no type conversion + else: + try: + raw_keys[k] = _yaml_types_to_parser[type(raw_data_from_yaml[k])]( + new_proposal + ) # take the command line value, but type it like the config value. + except ValueError as e: + raise ValueError( + f"Couldn't parse value from CLI or ENV '{new_proposal}' for key '{k}'") from e + + return updated_keys + + def _load_config(self, config_name: str) -> dict[str, Any]: + """Loads the YAML config from a file with a given name.""" + with open(config_name, "r", encoding="utf-8") as yaml_file: + raw_data_from_yaml = yaml.safe_load(yaml_file) + + # Load data from parent config. Note that inheritance has override + # semantics, and the path is relative to the current config. + if _BASE_CONFIG_ATTR in raw_data_from_yaml: + parent_config_filename = raw_data_from_yaml[_BASE_CONFIG_ATTR] + if not os.path.isabs(parent_config_filename): + loaded_parent_config_filename = os.path.join( + os.path.dirname(config_name), parent_config_filename + ) + if not os.path.isfile(loaded_parent_config_filename): + dir_path = os.path.dirname(os.path.realpath(__file__)) + loaded_parent_config_filename = os.path.join( + dir_path, f"configs/{parent_config_filename}" + ) + else: + loaded_parent_config_filename = parent_config_filename + + base_config = self._load_config(loaded_parent_config_filename) + for key, value in raw_data_from_yaml.items(): + base_config[key] = value + return base_config + return raw_data_from_yaml + + def __init__(self, argv: list[str], **kwargs): + config_name : str = argv[1] + raw_data_from_yaml = self._load_config(config_name) + + self._validate_env_variables(raw_data_from_yaml) + + raw_keys = OrderedDict() + keys_from_env_and_command_line = self._update_from_env_and_command_line(raw_keys, raw_data_from_yaml, argv, **kwargs) + max_logging.log( + f"Updating keys from env and command line: {keys_from_env_and_command_line}") + keys_from_model = _HyperParameters.update_model_vars(argv[1], raw_keys, config_name) + max_logging.log(f"Updating keys from model: {keys_from_model}") + validate_no_keys_overwritten_twice(keys_from_env_and_command_line, keys_from_model) + + # We initialize the jax distributed system here because it must be done before device backend is initialized. + max_utils.maybe_initialize_jax_distributed_system(raw_keys) + + if raw_keys['jax_cache_dir']: + compilation_cache.set_cache_dir(os.path.expanduser(raw_keys['jax_cache_dir'])) + + if raw_keys['model_name'] == "gpt3-175b": + _HyperParameters.configure_gpt3_task(raw_keys) + _HyperParameters.user_init(raw_keys) + + self.keys = raw_keys + keys = [k for k in raw_keys] # pylint: disable=unnecessary-comprehension + keys.sort() + for k in keys: + max_logging.log(f"Config param {k}: {raw_keys[k]}") + + @staticmethod + def user_init(raw_keys): + '''Transformations between the config data and configs used at runtime''' + if raw_keys["run_name"] == "": + raw_keys["run_name"] = os.environ.get("JOBSET_NAME") #using XPK default + run_name = raw_keys["run_name"] + base_output_directory = raw_keys["base_output_directory"] + if run_name: + raw_keys["tensorboard_dir"] = os.path.join(base_output_directory, run_name, "tensorboard", "") + raw_keys["checkpoint_dir"] = os.path.join(base_output_directory, run_name, "checkpoints", "") + raw_keys["metrics_dir"] = os.path.join(base_output_directory, run_name, "metrics", "") + + if raw_keys["learning_rate_schedule_steps"]==-1: + raw_keys["learning_rate_schedule_steps"] = raw_keys["steps"] + if raw_keys["steps"]==-1: + raw_keys["steps"] = raw_keys["learning_rate_schedule_steps"] + + emb_scale, num_head_scale, mlp_dim_scale, layer_scale = get_individual_scales(raw_keys['global_parameter_scale']) + raw_keys['emb_dim'] = 2**emb_scale * raw_keys['base_emb_dim'] + raw_keys['num_query_heads'] = 2**num_head_scale * raw_keys['base_num_query_heads'] + raw_keys['num_kv_heads'] = 2**num_head_scale * raw_keys['base_num_kv_heads'] + raw_keys['mlp_dim'] = 2**mlp_dim_scale * raw_keys['base_mlp_dim'] + raw_keys['num_decoder_layers'] = 2**layer_scale * raw_keys['base_num_decoder_layers'] + + raw_keys['global_batch_size_to_load'], raw_keys['global_batch_size_to_train_on'] = \ + calculate_global_batch_sizes(raw_keys) + raw_keys['num_slices'] = get_num_slices(raw_keys) + raw_keys['quantization_local_shard_count'] = get_quantization_local_shard_count(raw_keys) + + print_system_information() + + # Write raw_keys to GCS before type conversions + max_utils.write_config_raw_keys_for_gcs(raw_keys) + + # Type conversions + raw_keys["dtype"] = jax.numpy.dtype(raw_keys["dtype"]) + raw_keys["logical_axis_rules"] = _lists_to_tuples(raw_keys["logical_axis_rules"]) + raw_keys["data_sharding"] = _lists_to_tuples(raw_keys["data_sharding"]) + + validate_keys(raw_keys) + + @staticmethod + def configure_gpt3_task(raw_keys): + '''dynamically configure gpt3 task based on training rules''' + # follow https://github.com/google/paxml/blob/19db52eed85ae0d2365339b83a97cd0b873bbf73/paxml/tasks/lm/params/c4.py#L280 + # according to training_rules of mlperf gpt3 training + global_batch_size = calculate_global_batch_sizes(raw_keys)[1] + if global_batch_size <= 3584: + raw_keys['learning_rate'] = 2e-5 + else: + raw_keys['learning_rate'] = 3e-5 + warmup_steps = math.ceil(265.0 * 1536 / global_batch_size - 1e-6) + decay_end_step = math.ceil(108600.0 * 1536 / global_batch_size - 1e-6) + raw_keys['learning_rate_schedule_steps'] = decay_end_step + raw_keys['warmup_steps_fraction'] = warmup_steps / decay_end_step + global_batch_size_to_train_on = calculate_global_batch_sizes(raw_keys)[1] + raw_keys['eval_interval'] = math.ceil(24567 / global_batch_size_to_train_on) + + @staticmethod + def update_model_vars(base_config_path, raw_keys, config_name : str): + ''' Update model config variables + ''' + validate_model_name(raw_keys['model_name']) + max_logging.log(f"Running Model: {raw_keys['model_name']}") + + updated_keys = [] + if raw_keys['model_name'] != 'default': + model_name = raw_keys['model_name'] + # First look at the model configs next to the base_config_path, and + # fallback to the python codebase if the config cannot be found. + file_path = os.path.join( + os.path.dirname(base_config_path), f"models/{model_name}.yml" + ) + if not os.path.isfile(file_path): + dir_path = os.path.dirname(os.path.realpath(__file__)) + file_path = os.path.join(dir_path, f"configs/models/{model_name}.yml") + with open(file_path, 'r', encoding="utf-8") as file: + model_vars = yaml.safe_load(file) + updated_keys = list(model_vars.keys()) + raw_keys = validate_and_update_keys(raw_keys, model_vars, config_name) + return updated_keys + +def validate_and_update_keys(raw_keys, model_keys, config_name : str): + ''' Validate and update model specific config keys + ''' + max_logging.log("Updating following parameters in config\n") + for k in model_keys: + max_logging.log(f"{k}: {model_keys[k]}") + if k not in raw_keys: + raise ValueError(f'Key {k} does not exist in config {config_name}.') + elif not isinstance(raw_keys[k], type(model_keys[k])): + raise ValueError(f'Type of key:{k} does not match with {type(model_keys[k])}') + else: + raw_keys[k] = model_keys[k] + return raw_keys + +def get_individual_scales(scale): + '''Choose appropriate scales for individual dimensions based on global scale + We choose to rotate between doubling: + num_head and mlp_dim + embed_dim + num_layers + Any one of these steps is not a perfect doubling, although going through a cycle + of three is a near perfect 8x scaling except for the linear -> softmax -> output step''' + + + log_2_scale = math.floor((math.log2(scale))) + if 2**log_2_scale != scale: + raise ValueError("Global parameter scale should be a power of 2. If you want finer grained control of the model sizes " + "then you can explicitly set base_embed_dim, base_num_heads, base_mlp_dim, base_num_decoder_layers and/or head_dim.") + base_scale, rem = divmod(log_2_scale, 3) + num_head_scale = base_scale + int(rem > 0) + mlp_dim_scale = num_head_scale + emb_scale = base_scale + int(rem > 1) + layer_scale = base_scale + return emb_scale, num_head_scale, mlp_dim_scale, layer_scale + +def calculate_global_batch_sizes(raw_keys): + """ Calculates target global batch size from target devices and per_device_batch""" + per_device_batch_size = raw_keys['per_device_batch_size'] + num_devices = get_num_target_devices(raw_keys) + if per_device_batch_size < 1.0: + # For per_device_batch_size<1, we load the data as if per_device_batch_size=1 + global_batch_size_to_load = num_devices + else: + global_batch_size_to_load = int(num_devices * per_device_batch_size) + + global_batch_size_to_train_on = int(num_devices * per_device_batch_size) + return global_batch_size_to_load, global_batch_size_to_train_on + +def get_num_target_devices(raw_keys): + compile_topology = accelerator_to_spec_map.get_system_characteristics(raw_keys.get('compile_topology', "")) + if compile_topology is not None: + devices_per_slice = compile_topology.devices_per_slice + return int(devices_per_slice * raw_keys['compile_topology_num_slices']) + else: + return len(jax.devices()) + +def get_num_slices(raw_keys): + if int(raw_keys['compile_topology_num_slices']) > 0: + return raw_keys['compile_topology_num_slices'] + else: + devices = jax.devices() + try: + return 1 + max([d.slice_index for d in devices]) + except: + return 1 + +def get_quantization_local_shard_count(raw_keys): + if raw_keys['quantization_local_shard_count'] == -1: + return raw_keys['num_slices'] + else: + return raw_keys['quantization_local_shard_count'] + +class HyperParameters(): # pylint: disable=missing-class-docstring + def __init__(self): + pass + + def __getattr__(self, attr): + if attr not in _config.keys: + raise ValueError(f"Requested key {attr}, not in config") + return _config.keys[attr] + + def __setattr__(self, attr, value): + raise ValueError + + def get_keys(self): + return _config.keys + +def initialize(argv, **kwargs): + global _config, config + _config = _HyperParameters(argv, **kwargs) + config = HyperParameters() + +if __name__ == "__main__": + initialize(sys.argv) + print(config.steps) + r = range(config.steps) diff --git a/maxtext-setup/maxtext/MaxText/pytest.ini b/maxtext-setup/maxtext/MaxText/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..fa8e8142beb9a5fa4a7592ede6b087dfaef27a57 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/pytest.ini @@ -0,0 +1,13 @@ +# pytest.ini +[pytest] +testpaths = + tests +python_files = *_test.py +addopts = + -rf --import-mode=importlib + --ignore=tests/profiler_test.py + --ignore=tests/train_smoke_test.py + --ignore=tests/train_int8_smoke_test.py + --ignore=tests/train_gpu_smoke_test.py +markers = + tpu: marks tests to be run on TPU \ No newline at end of file diff --git a/maxtext-setup/maxtext/MaxText/sequence_packing.py b/maxtext-setup/maxtext/MaxText/sequence_packing.py new file mode 100644 index 0000000000000000000000000000000000000000..36bccde0c9299b450044b4117b3094e18f513b1c --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/sequence_packing.py @@ -0,0 +1,207 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Packed Sequence Op.""" + +from typing import Dict, Optional, List, Union + +import tensorflow as tf + +AUTOTUNE = tf.data.experimental.AUTOTUNE + + +def pack_dataset(dataset: tf.data.Dataset, + key2length: Union[int, Dict[str, int]], + keys: Optional[List[str]] = None) -> tf.data.Dataset: + """Creates a 'packed' version of a dataset on-the-fly. + Adapted from the mesh-tf implementation. + This is meant to replace the irritation of having to create a separate + "packed" version of a dataset to train efficiently on TPU. + Each example in the output dataset represents several examples in the + input dataset. + For each key in the input dataset, two additional keys are created: + _segmentation: an int32 tensor identifying the parts + representing the original example. + _position: an int32 tensor identifying the position within the original + example. + Example: + Two input examples get combined to form an output example. + The input examples are: + {"inputs": [8, 7, 1, 0], "targets":[4, 1, 0]} + {"inputs": [2, 3, 4, 1], "targets":[5, 6, 1]} + The output example is: + { + "inputs": [8, 7, 1, 2, 3, 4, 1, 0, 0, 0] + "inputs_segmentation": [1, 1, 1, 2, 2, 2, 2, 0, 0, 0] + "inputs_position": [0, 1, 2, 0, 1, 2, 3, 0, 0, 0] + "targets": [4, 1, 5, 6, 1, 0, 0, 0, 0, 0] + "targets_segmentation": [1, 1, 2, 2, 2, 0, 0, 0, 0, 0] + "targets_position": [0, 1, 0, 1, 2, 0, 0, 0, 0, 0] + } + 0 represents padding in both the inputs and the outputs. + Sequences in the incoming examples are truncated to length "length", and the + sequences in the output examples all have fixed (padded) length "length". + Args: + dataset: a tf.data.Dataset + key2length: an integer, or a dict from feature-key to integer + keys: a list of strings (e.g. ["inputs", "targets"]) + Returns: + a tf.data.Dataset + """ + shapes = tf.nest.map_structure(lambda spec: spec.shape, dataset.element_spec) + if keys is None: + keys = list(shapes.keys()) + for k in keys: + if k not in shapes: + raise ValueError(f"""Key {k} not found in dataset. Available keys are + {shapes.keys()}""") + if not shapes[k].is_compatible_with(tf.TensorShape([None])): + raise ValueError('Tensors to be packed must be one-dimensional.') + # make sure that the length dictionary contains all keys as well as the + # keys suffixed by "_segmentation" and "_position" + if isinstance(key2length, int): + key2length = {k: key2length for k in keys} + for k in keys: + for suffix in ['_segmentation', '_position']: + key2length[k + suffix] = key2length[k] + + # trim to length + dataset = dataset.map( + lambda x: {k: x[k][:key2length[k]] for k in keys}, + num_parallel_calls=AUTOTUNE) + # Setting batch_size=length ensures that the concatenated sequences (if they + # have length >=1) are sufficient to fill at least one packed example. + batch_size = max(key2length.values()) + # We pad with a negative value instead of the default 0 because 0 is a + # valid token for some tokenizers for e.g., representing unknown value + dataset = dataset.padded_batch( + batch_size, padded_shapes={k: [-1] for k in keys}, padding_values=-1) + dataset = _pack_with_tf_ops(dataset, keys, key2length) + + # Set the Tensor shapes correctly since they get lost in the process. + def my_fn(x): + return {k: tf.reshape(v, [key2length[k]]) for k, v in x.items()} + + return dataset.map(my_fn, num_parallel_calls=AUTOTUNE) + + +def _pack_with_tf_ops(dataset: tf.data.Dataset, keys: List[str], + key2length: Dict[str, int]) -> tf.data.Dataset: + """Helper-function for packing a dataset which has already been batched. + Helper for pack_dataset() Uses tf.while_loop. + Args: + dataset: a dataset containing padded batches of examples. + keys: a list of strings + key2length: an dict from feature-key to integer + Returns: + a dataset. + """ + empty_example = {} + for k in keys: + empty_example[k] = tf.zeros([0], dtype=tf.int32) + empty_example[k + '_position'] = tf.zeros([0], dtype=tf.int32) + keys_etc = empty_example.keys() + + def write_packed_example(partial, outputs): + new_partial = empty_example.copy() + new_outputs = {} + for k in keys_etc: + new_outputs[k] = outputs[k].write( + outputs[k].size(), + tf.pad(partial[k], [[0, key2length[k] - tf.size(partial[k])]])) + return new_partial, new_outputs + + def map_fn(x): + """Internal function to flat_map over. + Consumes a batch of input examples and produces a variable number of output + examples. + Args: + x: a single example + Returns: + a tf.data.Dataset + """ + partial = empty_example.copy() + i = tf.zeros([], dtype=tf.int32) + dynamic_batch_size = tf.shape(x[keys[0]])[0] + outputs = {} + for k in keys: + outputs[k] = tf.TensorArray( + tf.int32, size=0, dynamic_size=True, element_shape=[key2length[k]]) + outputs[k + '_position'] = tf.TensorArray( + tf.int32, size=0, dynamic_size=True, element_shape=[key2length[k]]) + + def body_fn(i, partial, outputs): + """Body function for while_loop. + Args: + i: integer scalar + partial: dictionary of Tensor (partially-constructed example) + outputs: dictionary of TensorArray + Returns: + A triple containing the new values of the inputs. + """ + can_append = True + one_example = {} + for k in keys: + val = tf.cast(x[k][i], tf.int32) + # We consider only the valid tokens i.e., token_id != -1 + val = val[:tf.reduce_sum(tf.cast(tf.not_equal(val, -1), tf.int32))] + one_example[k] = val + for k in keys: + can_append = tf.logical_and( + can_append, + tf.less_equal( + tf.size(partial[k]) + tf.size(one_example[k]), key2length[k])) + + def false_fn(): + return write_packed_example(partial, outputs) + + def true_fn(): + return partial, outputs + + partial, outputs = tf.cond(can_append, true_fn, false_fn) + new_partial = {} + for k in keys: + new_seq = one_example[k][:key2length[k]] + new_seq_len = tf.size(new_seq) + new_partial[k] = tf.concat([partial[k], new_seq], 0) + new_partial[k + '_position'] = tf.concat( + [partial[k + '_position'], + tf.range(new_seq_len)], 0) + partial = new_partial + return i + 1, partial, outputs + + # For loop over all examples in the batch. + i, partial, outputs = tf.while_loop( + cond=lambda *_: True, + body=body_fn, + loop_vars=(i, partial, outputs), + shape_invariants=( + tf.TensorShape([]), + {k: tf.TensorShape([None]) for k in keys_etc}, + {k: tf.TensorShape(None) for k in keys_etc}, + ), + maximum_iterations=dynamic_batch_size) + _, outputs = write_packed_example(partial, outputs) + packed = {k: outputs[k].stack() for k in keys_etc} + for k in keys: + packed[k + '_segmentation'] = ( + tf.cumsum( + tf.cast(tf.equal(packed[k + '_position'], 0), tf.int32), axis=1) * + tf.cast(tf.not_equal(packed[k], 0), tf.int32)) + return packed + + dataset = dataset.map(map_fn, num_parallel_calls=AUTOTUNE) + return dataset.unbatch() diff --git a/maxtext-setup/maxtext/MaxText/standalone_checkpointer.py b/maxtext-setup/maxtext/MaxText/standalone_checkpointer.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf462e1dcaf4a08a6b9db767a2e4ad01b62e9ee --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/standalone_checkpointer.py @@ -0,0 +1,102 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=g-bad-todo, abstract-method, consider-using-with, ungrouped-imports +"""Standalone checkpointer - only saves and restores checkpoints at regular intervals, accesses storage needs.""" + +# Calling jax.device_count here prevents a "TPU platform already registered" error. +# See github.com/google/maxtext/issues/20 for more + +import datetime +import os + +from typing import Sequence +from absl import app +from flax.linen import partitioning as nn_partitioning +import jax +import numpy as np + +import checkpointing +import max_utils +import max_logging +import pyconfig +from train import setup_mesh_and_model, get_first_step, validate_train_config, save_checkpoint + +from layers import models + +Transformer = models.Transformer + +def checkpoint_loop(config, state=None): + """Main Checkpointing loop. + Saves checkpoints. + Args: + config: + state: + ckpt_path: + Returns: + """ + init_rng, writer, checkpoint_manager, mesh, model, _, tx = setup_mesh_and_model(config) + + unboxed_abstract_state, _, _ = max_utils.get_abstract_state(model, tx, + config, init_rng, mesh, is_training=True) + # A barrier to sync all hosts before starting to restore checkpoint + jax.experimental.multihost_utils.sync_global_devices("Barrier before load") + checkpoint_load_start = datetime.datetime.now() + with nn_partitioning.axis_rules(config.logical_axis_rules): + state, _ = checkpointing.load_state_if_possible(checkpoint_manager, + None, + config.load_parameters_path, + config.load_full_state_path, + unboxed_abstract_state) + jax.block_until_ready(state) + checkpoint_load_end = datetime.datetime.now() + if state is not None: # Checkpoint was available for restore + if jax.process_index() == 0: + max_logging.log(f"STANDALONE CHECKPOINTER : Checkpoint restored in : {checkpoint_load_end - checkpoint_load_start}") + else: # Checkpoint was unavailable, state needs to be initialized + state, _, _ = max_utils.setup_training_state(model, None, + tx, config, init_rng, mesh, checkpoint_manager) + + start_step = get_first_step(state) # this is the start_step for training + for step in np.arange(start_step, config.steps): + if checkpoint_manager is not None: + start_time = datetime.datetime.now() + # A barrier to sync all hosts before starting to save checkpoint + jax.experimental.multihost_utils.sync_global_devices("Barrier before save") + if save_checkpoint(checkpoint_manager, step, state): + checkpoint_manager.wait_until_finished() + end_time = datetime.datetime.now() + if jax.process_index() == 0: + max_logging.log(f"STANDALONE CHECKPOINTER : Checkpoint saved in {end_time - start_time} ,step {step}, on host 0") + + max_utils.close_summary_writer(writer) + return state + +def main(argv: Sequence[str]) -> None: + jax.config.update('jax_cpu_enable_gloo_collectives', True) + os.environ["TF_CPP_MIN_LOG_LEVEL"] = "0" + pyconfig.initialize(argv) + config = pyconfig.config + validate_train_config(config) + print(f"Found {jax.device_count()} devices.") + print(f"Found {jax.process_count()} processes.") + print(f"Found {jax.devices()} devices.") + os.environ["TFDS_DATA_DIR"] = config.dataset_path + checkpoint_loop(config) + + +if __name__ == "__main__": + app.run(main) diff --git a/maxtext-setup/maxtext/MaxText/standalone_dataloader.py b/maxtext-setup/maxtext/MaxText/standalone_dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb13e4dc47f246b231a7e225f545b3e13ca07e9 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/standalone_dataloader.py @@ -0,0 +1,75 @@ +""" + Copyright 2023 Google LLC + 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. + """ + +# pylint: disable=g-bad-todo, abstract-method, consider-using-with, ungrouped-imports +""" Standalone data loader - only loads data for each training step, accesses storage needs.""" + +# Calling jax.device_count here prevents a "TPU platform already registered" error. +# See github.com/google/maxtext/issues/20 for more +import jax +import os + +import max_logging + +from typing import Sequence +import datetime +from absl import app +import numpy as np + +import pyconfig +from train import validate_train_config, get_first_step, load_next_batch, setup_train_loop + + +def data_load_loop(config, state=None): + """Main data loader loop. + Loads batches of data for each training step. + """ + _, _, _, _, _, _, _, data_iterator, _, state = setup_train_loop(config) + + example_batch = None + + start = datetime.datetime.now() + start_step = get_first_step(state) + example_batch = load_next_batch(data_iterator, example_batch, config) + jax.block_until_ready(example_batch) + first_end = datetime.datetime.now() + time_to_load_first_batch = first_end-start + if jax.process_index() == 0: + max_logging.log(f"STANDALONE DATALOADER : First step completed in {time_to_load_first_batch} seconds, on host 0") + + for _ in np.arange(start_step+1, config.steps): + example_batch = load_next_batch(data_iterator, example_batch, config) + + jax.block_until_ready(example_batch) # wait until the last batch is read + end = datetime.datetime.now() + if jax.process_index() == 0: + max_logging.log(f"STANDALONE DATALOADER : {config.steps} batches loaded in {end-start} seconds, on host 0") + return state + + +def main(argv: Sequence[str]) -> None: + jax.config.update('jax_cpu_enable_gloo_collectives', True) + os.environ["TF_CPP_MIN_LOG_LEVEL"] = "0" + pyconfig.initialize(argv) + config = pyconfig.config + validate_train_config(config) + max_logging.log(f"Found {jax.device_count()} devices.") + max_logging.log(f"Found {jax.process_count()} processes.") + max_logging.log(f"Found {jax.devices()} devices.") + os.environ["TFDS_DATA_DIR"] = config.dataset_path + data_load_loop(config) + + + +if __name__ == "__main__": + app.run(main) diff --git a/maxtext-setup/maxtext/MaxText/tests/attention_test.py b/maxtext-setup/maxtext/MaxText/tests/attention_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e69c2306dcab57c950c275a030f765bd1718c3ac --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/attention_test.py @@ -0,0 +1,270 @@ +# Copyright 2023 Google LLC +# +# 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. + +"""Tests for Attentions.""" + +import sys +import unittest + +import common_types + +from flax.core import freeze +import jax +import jax.numpy as jnp +import max_utils +import numpy as np +import pytest + +import pyconfig + +from layers import attentions +from layers import embeddings + +Mesh = jax.sharding.Mesh +Attention = attentions.Attention + + +class AttentionTest(unittest.TestCase): + """Test for the Attention """ + def setUp(self): + super().setUp() + pyconfig.initialize([sys.argv[0], 'configs/base.yml'], per_device_batch_size = 1.0, run_name='test', enable_checkpointing=False, max_target_length=128, max_prefill_predict_length=16 ) + self.cfg = pyconfig.config + self.rng = jax.random.PRNGKey(0) + + devices_array = max_utils.create_device_mesh(self.cfg) + self.mesh = Mesh(devices_array, self.cfg.mesh_axes) + + self.global_batch_size = self.cfg.global_batch_size_to_train_on + self.num_kv_heads = self.cfg.num_kv_heads + self.num_query_heads = self.cfg.num_query_heads + self.max_target_length = self.cfg.max_target_length + self.head_dim = self.cfg.head_dim + self.embed_dim = self.cfg.base_emb_dim + self.dtype = self.cfg.dtype + + self._attention_as_mha_generic = Attention( + config=self.cfg, + num_query_heads=self.num_query_heads, + num_kv_heads=self.num_kv_heads, + head_dim=self.head_dim, + max_target_length=self.max_target_length, + max_prefill_predict_length=self.cfg.max_prefill_predict_length, + mesh=self.mesh, + attention_kernel = "dot_product", + dtype=self.dtype, + dropout_rate=self.cfg.dropout_rate, + name='self_attention', + ) + + self._attention_as_mha_generic_variable = self._attention_as_mha_generic.init( + {'params': self.rng, 'aqt': self.rng}, + jnp.ones( + (self.global_batch_size, self.max_target_length, self.embed_dim)), + jnp.ones( + (self.global_batch_size, self.max_target_length, self.embed_dim)), + jnp.ones( + (self.global_batch_size, self.max_target_length)), + ) + + def get_data(self, dtype): + lnx = jax.random.normal( + self.rng, + shape=(self.global_batch_size, self.max_target_length, self.embed_dim), + dtype=dtype, + ) + + decoder_segment_ids = jax.random.randint(self.rng, (self.global_batch_size, self.max_target_length), 0, 4) + decoder_positions = jax.random.randint(self.rng, (self.global_batch_size, self.max_target_length), 0, self.max_target_length) + + return lnx, decoder_segment_ids, decoder_positions + + def get_structured_data(self, dtype): + lnx = jax.random.normal( + self.rng, + shape=(self.global_batch_size, self.max_target_length, self.embed_dim), + dtype=dtype, + ) + + decoder_positions = jnp.stack([ + jnp.arange(self.max_target_length, dtype=jnp.int32) + for _ in range(self.global_batch_size) + ]) + + decoder_segment_ids = jax.numpy.zeros((self.global_batch_size, self.max_target_length))\ + + common_types.DECODING_ACTIVE_SEQUENCE_INDICATOR + + return lnx, decoder_segment_ids, decoder_positions + + @pytest.mark.tpu + def test_autoregression(self): + prefill_length = self.cfg.max_prefill_predict_length + decode_total_length = self.cfg.max_target_length + lnx, decoder_segment_ids, decoder_positions = self.get_structured_data( + self.dtype) + + mha_full = self._attention_as_mha_generic.apply( + self._attention_as_mha_generic_variable, + lnx, + lnx, + decoder_segment_ids=decoder_segment_ids, + inputs_positions=decoder_positions, + deterministic=True, + model_mode=common_types.MODEL_MODE_TRAIN, + rngs={'aqt': self.rng}, + ) + + lnx_prefill = lnx[:, 0:prefill_length, :] + decoder_segment_ids_prefill = decoder_segment_ids[:, 0:prefill_length] + decoder_positions_prefill = decoder_positions[:, 0:prefill_length] + + mha_prefill, output_cache = self._attention_as_mha_generic.apply( + self._attention_as_mha_generic_variable, + lnx_prefill, + lnx_prefill, + decoder_segment_ids=decoder_segment_ids_prefill, + inputs_positions=decoder_positions_prefill, + deterministic=True, + model_mode=common_types.MODEL_MODE_PREFILL, + rngs={'aqt': self.rng}, + mutable=["cache"] + ) + + self.assertTrue( + jax.numpy.allclose( + mha_prefill, mha_full[:,:prefill_length,:], rtol=1e-02, atol=1e-02, equal_nan=False + ) + ) + + for idx in range(prefill_length, decode_total_length): + lnx_idx = lnx[:, idx:idx+1, :] + decoder_positions_idx = decoder_positions[:, idx:idx+1] + self._attention_as_mha_generic_variable.update(output_cache) + mha_idx, output_cache = self._attention_as_mha_generic.apply( + self._attention_as_mha_generic_variable, + lnx_idx, + lnx_idx, + inputs_positions=decoder_positions_idx, + deterministic=True, + model_mode=common_types.MODEL_MODE_AUTOREGRESSIVE, + rngs={'aqt': self.rng}, + mutable=["cache"] + ) + + mha_full_this_idx = mha_full[:,idx:idx+1,:] + self.assertTrue( + mha_full_this_idx.shape == mha_idx.shape + ) + self.assertTrue( + jax.numpy.allclose( + mha_full_this_idx, mha_idx, rtol=1e-02, atol=1e-02, equal_nan=False + ) + ) + + @pytest.mark.tpu + def test_tpu_kernel_attention_mha(self): + self.tpu_kernel_attention_helper(self.num_kv_heads) + + @pytest.mark.tpu + def test_tpu_kernel_attention_gqa(self): + self.tpu_kernel_attention_helper(self.num_kv_heads // 2) + + @pytest.mark.tpu + def test_tpu_kernel_attention_mqa(self): + self.tpu_kernel_attention_helper(1) + + def tpu_kernel_attention_helper(self, num_kv_heads): + """Test equalvant between dot_product and TPU accelerated""" + + lnx, decoder_segment_ids, decoder_positions = self.get_data( + self.dtype) + + attention_as_mha_generic = Attention( + config=self.cfg, + num_query_heads=self.num_query_heads, + num_kv_heads=num_kv_heads, + head_dim=self.head_dim, + max_target_length=self.max_target_length, + max_prefill_predict_length=self.cfg.max_prefill_predict_length, + mesh=self.mesh, + attention_kernel = "dot_product", + dtype=self.dtype, + dropout_rate=self.cfg.dropout_rate, + name='self_attention', + ) + + attention_as_mha_generic_variable = attention_as_mha_generic.init( + {'params': self.rng, 'aqt': self.rng}, + jnp.ones( + (self.global_batch_size, self.max_target_length, self.embed_dim)), + jnp.ones( + (self.global_batch_size, self.max_target_length, self.embed_dim)), + jnp.ones( + (self.global_batch_size, self.max_target_length)), + ) + + mha_generic_output = attention_as_mha_generic.apply( + attention_as_mha_generic_variable, + lnx, + lnx, + decoder_segment_ids=decoder_positions, + inputs_positions=decoder_segment_ids, + deterministic=True, + model_mode=common_types.MODEL_MODE_TRAIN, + rngs={'aqt': self.rng}, + ) + + attention_as_mha_flash = Attention( + config=self.cfg, + num_query_heads=self.num_query_heads, + num_kv_heads=num_kv_heads, + head_dim=self.head_dim, + max_target_length=self.max_target_length, + max_prefill_predict_length=self.cfg.max_prefill_predict_length, + mesh=self.mesh, + attention_kernel = "flash", + dtype=self.dtype, + dropout_rate=self.cfg.dropout_rate, + name='self_attention', + ) + + attention_as_mha_flash_variable = attention_as_mha_flash.init( + {'params': self.rng, 'aqt': self.rng}, + jnp.ones( + (self.global_batch_size, self.max_target_length, self.embed_dim)), + jnp.ones( + (self.global_batch_size, self.max_target_length, self.embed_dim)), + jnp.ones( + (self.global_batch_size, self.max_target_length)), + ) + + mha_generic_flash_output = attention_as_mha_flash.apply( + attention_as_mha_flash_variable, + lnx, + lnx, + decoder_segment_ids=decoder_positions, + inputs_positions=decoder_segment_ids, + deterministic=True, + model_mode=common_types.MODEL_MODE_TRAIN, + rngs={'aqt': self.rng}, + ) + + self.assertTrue( + jax.numpy.allclose( + mha_generic_output, mha_generic_flash_output, rtol=1e-01, atol=1e-01, equal_nan=False + ) + ) + +if __name__ == '__main__': + unittest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/gpt3_test.py b/maxtext-setup/maxtext/MaxText/tests/gpt3_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4650824bf0457f4cdc250afca92f69a7da74d5ce --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/gpt3_test.py @@ -0,0 +1,111 @@ + +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Tests for GPT3 """ +import sys +import jax +import unittest +import max_utils +from jax.sharding import Mesh +from layers import models +from layers import embeddings +from layers import quantizations + +import jax.numpy as jnp + +import pyconfig +import pytest + + +Mesh = jax.sharding.Mesh +Embed = embeddings.Embed + + +def init_random_model_vars(model, rng, example_batch): + """initialze random model vars.""" + model_vars = model.init( + {'params': rng, 'aqt': rng}, + example_batch['inputs'], + example_batch['inputs_position'], + enable_dropout=False, + ) + def _replace_initialization(key, value): + keystr = jax.tree_util.keystr(key) + # replace zero initializer to ensure strong test cases + # including Gpt3LayerNorm scale, Gpt3LayerNorm bias, and DenseGeneral bias + if "scale" in keystr or "bias" in keystr: + value = jax.nn.initializers.normal(1.0)(rng, value.shape, dtype=value.dtype) + return value + + model_vars = jax.tree_util.tree_map_with_path(_replace_initialization, model_vars) + return model_vars + + +class GPT3(unittest.TestCase): + """numerical tests for GPT3.""" + def setUp(self): + super().setUp() + pyconfig.initialize( + [sys.argv[0], 'configs/base.yml'], + run_name='test', + enable_checkpointing=False, + model_name='gpt3-52k', + dtype='float32', + ) + + self.cfg = pyconfig.config + self.rng = jax.random.PRNGKey(1234) + + devices_array = max_utils.create_device_mesh(self.cfg) + mesh = Mesh(devices_array, self.cfg.mesh_axes) + quant = quantizations.configure_quantization(self.cfg) + self.model = models.Transformer(config = self.cfg, mesh = mesh, quant = quant) + self.example_batch = { + 'inputs': jnp.array([[11, 12, 13, 14, 15]], dtype=jnp.int32), + 'inputs_position': jnp.array([[0, 1, 2, 3, 4]], dtype=jnp.int32), + 'inputs_segmentation': jnp.array([[1, 1, 1, 1, 1]], dtype=jnp.int32), + 'targets': jnp.array([[12, 13, 14, 15, 1]], dtype=jnp.int32), + 'targets_position': jnp.array([[0, 1, 2, 3, 4]], dtype=jnp.int32), + 'targets_segmentation': jnp.array([[1, 1, 1, 1, 0]], dtype=jnp.int32), + } + self.model_vars = init_random_model_vars(self.model, self.rng, self.example_batch) + + @pytest.mark.tpu + def test_logits_numerically(self): + # ground truth values are calculated from paxml after loading above model_vars + # note we expect all xents are the same except the padding one since: + # paxml applies padding in mlp layer + # while maxtext implementaiton applies padding in attention mask instead + # the two implementation are equivalent in valid non-padding tokens + per_example_xent_truth = jnp.array([[31.976467, 25.806253, 17.311134, 45.362663, 0.]], dtype=jnp.float32) + logits, _ = self.model.apply(self.model_vars, + self.example_batch['inputs'], + self.example_batch['inputs_position'], + decoder_segment_ids=self.example_batch['inputs_segmentation'], + enable_dropout=self.cfg.enable_dropout, + rngs={'dropout': self.rng, 'aqt': self.rng}, mutable='intermediates') + + one_hot_targets = jax.nn.one_hot(self.example_batch['targets'], self.cfg.vocab_size) + per_example_xent = -jnp.sum(jax.nn.log_softmax(logits) * one_hot_targets, axis=-1, dtype=jnp.float32) + # Mask out paddings at the end of each example. + per_example_xent = per_example_xent * (self.example_batch['targets_segmentation'] != 0) + + self.assertTrue( + jax.numpy.allclose( + per_example_xent, per_example_xent_truth, rtol=1e-03, atol=1e-03 + ) + ) diff --git a/maxtext-setup/maxtext/MaxText/tests/grain_data_processing_test.py b/maxtext-setup/maxtext/MaxText/tests/grain_data_processing_test.py new file mode 100644 index 0000000000000000000000000000000000000000..66c0b046f3c7c99da4164ea207aadfac203a04dc --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/grain_data_processing_test.py @@ -0,0 +1,139 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + + +import subprocess +import sys +import jax +from jax.sharding import Mesh +from jax.experimental import mesh_utils + +import unittest + +import pyconfig +from input_pipeline import _grain_data_processing + +class GrainDataProcessingTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + exit_code = subprocess.call(['bash','../setup_gcsfuse.sh', + 'DATASET_GCS_BUCKET=maxtext-dataset', + 'MOUNT_PATH=/tmp/gcsfuse']) + if exit_code != 0: + raise ValueError(f"Running setup_gcsfuse.sh failed with exit code: {exit_code}") + + def setUp(self): + super().setUp() + pyconfig.initialize([sys.argv[0], 'configs/base.yml'], + per_device_batch_size=1, + run_name='test', + mesh_axes = ['data'], + logical_axis_rules = [['batch', 'data']], + data_sharding = ['data'], + base_output_directory = "gs://max-experiments/", + dataset_path = "/tmp/gcsfuse", + tokenizer_path = "../assets/tokenizer", + enable_checkpointing=False, + dataset_type="c4-array_record", + dataset_name='array-record/c4/en/3.0.1', + eval_dataset_name='array-record/c4/en/3.0.1') + self.config = pyconfig.config + self.mesh_shape_1d = (len(jax.devices()),) + self.mesh = Mesh(mesh_utils.create_device_mesh(self.mesh_shape_1d), self.config.mesh_axes) + self.train_ds, self.eval_ds = self._get_datasets() + self.train_iter, self.eval_iter, self.predict_iter = self._get_preprocessed_datasets() + + def _get_datasets(self): + print("Sharding dataset in ", jax.process_count(), " shards") + train_ds, eval_ds = _grain_data_processing.get_datasets( + config=self.config) + return train_ds, eval_ds + + def _get_preprocessed_datasets(self): + train_iter, eval_iter, test_iter = _grain_data_processing.preprocess_dataset( + self.config, + self.mesh, + self.train_ds, self.eval_ds, + vocab_path=self.config.tokenizer_path) + return train_iter, eval_iter, test_iter + + def test_train_ds(self): + expected_shape = [jax.device_count(), self.config.max_target_length] + # For training we pack multiple short examples in one example. + # *_position and *_segmentation indicate the boundaries. + batch = next(self.train_iter) + self.assertEqual({k: list(v.shape) for k, v in batch.items()}, { + 'inputs': expected_shape, + 'inputs_position': expected_shape, + 'inputs_segmentation': expected_shape, + 'targets': expected_shape, + 'targets_position': expected_shape, + 'targets_segmentation': expected_shape, + }) + + def test_eval_ds(self): + expected_shape = [jax.device_count(), self.config.max_target_length] + batch = next(self.eval_iter) + self.assertEqual({k: list(v.shape) for k, v in batch.items()}, { + 'inputs': expected_shape, + 'inputs_position': expected_shape, + 'inputs_segmentation': expected_shape, + 'targets': expected_shape, + 'targets_position': expected_shape, + 'targets_segmentation': expected_shape, + }) + + + def test_predict_ds(self): + expected_shape = [jax.device_count(), self.config.max_target_length] + batch = next(self.predict_iter) + self.assertEqual({k: list(v.shape) for k, v in batch.items()}, { + 'inputs': expected_shape, + 'inputs_position': expected_shape, + 'inputs_segmentation': expected_shape, + 'targets': expected_shape, + 'targets_position': expected_shape, + 'targets_segmentation': expected_shape, + }) + + def test_batch_determinism(self): + batch1 = next(self.train_iter) + self.train_ds, _ = self._get_datasets() + train_iter, _, _= self._get_preprocessed_datasets() + batch2 = next(train_iter) + self.assertTrue((batch1['inputs']==batch2['inputs']).all()) + self.assertTrue((batch1['targets']==batch2['targets']).all()) + self.assertTrue((batch1['inputs_segmentation']==batch2['inputs_segmentation']).all()) + self.assertTrue((batch1['targets_segmentation']==batch2['targets_segmentation']).all()) + self.assertTrue((batch1['inputs_position']==batch2['inputs_position']).all()) + self.assertTrue((batch1['targets_position']==batch2['targets_position']).all()) + + def test_for_loop_repeatable(self): + def get_first_batch(iterator): + batch = None + for batch in iterator: + break + return batch + + eval_batch1 = get_first_batch(self.eval_iter) + eval_batch2 = get_first_batch(self.eval_iter) + self.assertTrue((eval_batch1['inputs']==eval_batch2['inputs']).all()) + self.assertTrue((eval_batch1['targets']==eval_batch2['targets']).all()) + + +if __name__ == '__main__': + unittest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/inference_microbenchmark_smoke_test.py b/maxtext-setup/maxtext/MaxText/tests/inference_microbenchmark_smoke_test.py new file mode 100644 index 0000000000000000000000000000000000000000..274739a7fbfe3aa09075cbf85b40a761fa9db69f --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/inference_microbenchmark_smoke_test.py @@ -0,0 +1,41 @@ +"""Copyright 2024 Google LLC + +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. +""" + +""" Smoke test for inference microbenchmark""" +import pyconfig +import pytest +import unittest +from absl.testing import absltest +from inference_microbenchmark import main as inference_microbenchmark_main + + +class Inference_Microbenchmark(unittest.TestCase): + @pytest.mark.tpu + def test(self): + pyconfig.initialize([None, + "configs/tpu_smoke_test.yml", + "tokenizer_path=../assets/tokenizer.llama2", + "ici_autoregressive_parallelism=-1", + "ici_fsdp_parallelism=1", + "max_prefill_predict_length=1024", + "max_target_length=2048", + "scan_layers=false", + "weight_dtype=bfloat16", + ]) + inference_microbenchmark_main(pyconfig.config) + + +if __name__ == "__main__": + absltest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/llama_test.py b/maxtext-setup/maxtext/MaxText/tests/llama_test.py new file mode 100644 index 0000000000000000000000000000000000000000..38e1a7c624fb0d776eb4927c523658c70cf31de7 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/llama_test.py @@ -0,0 +1,135 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Tests for Llama """ +import jax +import unittest +import jax.numpy as jnp +from typing import Tuple +from layers.llama2 import embeddings +import numpy as np + + +""" +An example reference jax_llama RoPE implementation from https://github.com/Sea-Snell/ +Users should feel free to change and optimize the RoPE implementation in MaxText defined in layers.py +as long as it passes our tests. But they shouldn't change the "reference" implementation in +llama_test.py which is only to be used for comparison purpose. + +""" + +def precompute_freqs_cis( + dim: int, end: int, theta: float = 10000.0, dtype: jnp.dtype = jnp.float32 +) -> jnp.ndarray: + """Calculate the frequencies""" + freqs = 1.0 / ( + theta ** (np.arange(0, dim, 2)[: (dim // 2)].astype(dtype) / dim) + ) + t = np.arange(end) # type: ignore + freqs = np.outer(t, freqs).astype(dtype) # type: ignore + sin, cos = np.sin(freqs), np.cos(freqs) + freqs_cis = np.complex64(cos + 1j * sin) + return jnp.asarray(freqs_cis) + + + +def apply_rotary_emb( + xq: jnp.ndarray, + xk: jnp.ndarray, + freqs_cis: jnp.ndarray, + dtype: jnp.dtype = jnp.bfloat16, +) -> Tuple[jnp.ndarray, jnp.ndarray]: + """ Apply the computed Rotary Postional Embedding""" + reshape_xq = xq.astype(jnp.float32).reshape(*xq.shape[:-1], -1, 2) + reshape_xk = xk.astype(jnp.float32).reshape(*xk.shape[:-1], -1, 2) + + xq_ = jax.lax.complex(reshape_xq[..., 0], reshape_xq[..., 1]) + xk_ = jax.lax.complex(reshape_xk[..., 0], reshape_xk[..., 1]) + + # add head dim + freqs_cis = jnp.reshape( + freqs_cis, (*freqs_cis.shape[:2], 1, *freqs_cis.shape[2:]) + ) + + xq_out = xq_ * freqs_cis + xq_out = jnp.stack((jnp.real(xq_out), jnp.imag(xq_out)), axis=-1).reshape( + *xq_out.shape[:-1], -1 + ) + + xk_out = xk_ * freqs_cis + xk_out = jnp.stack((jnp.real(xk_out), jnp.imag(xk_out)), axis=-1).reshape( + *xk_out.shape[:-1], -1 + ) + + return xq_out.astype(dtype), xk_out.astype(dtype) + +def permute_to_match_maxtext_rope(arr): + evens = arr[..., ::2] + odds = arr[..., 1::2] + return jax.numpy.concatenate((evens, odds), axis=arr.ndim-1) + +class RoPETest(unittest.TestCase): + """Test for the RoPE implementation """ + def test_rope(self): + dim_per_head = 128 + seq_len = 8 + + # Run the two implementations on some random query and key + x_q = np.random.normal(1, 0.5, (1, seq_len, 4, dim_per_head)) + x_k = np.random.normal(1, 0.5, (1, seq_len, 4, dim_per_head)) + + # Calculate RoPE embeddings from Sea-Snell implementation + freqs_cis = precompute_freqs_cis(dim_per_head, seq_len * 2) + freqs_cis = jnp.take( + freqs_cis, jnp.arange(seq_len, dtype=np.int32)[None, :], axis=0 + ) + + llama_output = apply_rotary_emb( + jnp.asarray(x_q), jnp.asarray(x_k), freqs_cis + ) + + seq_length = x_q.shape[1] + position = jnp.arange(seq_length, dtype=jnp.float32)[jnp.newaxis, :] + + # Calculate RoPE embeddings from MaxText implementation + query_proj = embeddings.RotaryEmbedding(embedding_dims = dim_per_head)(permute_to_match_maxtext_rope(x_q), position = position) + key_proj = embeddings.RotaryEmbedding(embedding_dims = dim_per_head)(permute_to_match_maxtext_rope(x_k), position = position) + + # Compare results + self.assertTrue(jax.numpy.allclose(permute_to_match_maxtext_rope(llama_output[0]), query_proj, rtol=1e-01, atol=1e-04, equal_nan=False)) + self.assertTrue(jax.numpy.allclose(permute_to_match_maxtext_rope(llama_output[1]), key_proj, rtol=1e-01, atol=1e-04, equal_nan=False)) + + def test_scaling_rope(self): + dim_per_head = 128 + seq_len = 8 + + # Run the two implementations on some random query and key + x_q = np.random.normal(1, 0.5, (1, seq_len, 4, dim_per_head)) + position = jnp.arange(seq_len, dtype=jnp.float32)[jnp.newaxis, :] + + # Calculate RoPE embeddings and then scale + query_proj_1 = embeddings.RotaryEmbedding(embedding_dims = dim_per_head)(x_q, position = position) + query_proj_1 = query_proj_1 * (dim_per_head ** -0.5) + + # scale first and then apply RoPE + query_proj_2 = x_q * (dim_per_head ** -0.5) + query_proj_2 = embeddings.RotaryEmbedding(embedding_dims = dim_per_head)(query_proj_2, position=position) + + self.assertTrue(jax.numpy.allclose(query_proj_2, query_proj_1, rtol=1e-01, atol=1e-04, equal_nan=False)) + +if __name__ == '__main__': + unittest.main() + diff --git a/maxtext-setup/maxtext/MaxText/tests/max_utils_test.py b/maxtext-setup/maxtext/MaxText/tests/max_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..db87c60286b6b79897bdcca6002f02320bd0a20b --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/max_utils_test.py @@ -0,0 +1,151 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Tests for the common Max Utils """ +import jax +import max_utils +from flax import linen as nn +from flax.training import train_state +from jax import numpy as jnp +from jax import random +from jax.sharding import Mesh +import optax +import pyconfig +import unittest +from layers import models +from layers import quantizations + +Transformer = models.Transformer + +class MaxUtilsSummaryStats(unittest.TestCase): + """Tests for the summary stats functions in max_utils.py""" + def test_l2norm_pytree(self): + x = {'a': jax.numpy.array([0, 2, 0]), 'b': jax.numpy.array([0, 3, 6])} + pytree_l2_norm = max_utils.l2norm_pytree(x) + self.assertTrue(jax.numpy.allclose(pytree_l2_norm, 7, rtol=1e-05, atol=1e-08, equal_nan=False)) + +class MaxUtilsInitState(unittest.TestCase): + """Tests initialization of training and decode states in max_utils.py""" + def setUp(self): + self.model = nn.Dense(features=5) + self.key1, self.key2 = random.split(random.key(0)) + self.input = random.normal(self.key1, (10,)) # Dummy input data + self.params = self.model.init(self.key2, self.input) + self.output = self.model.apply(self.params, self.input) + self.tx = optax.adam(learning_rate=0.001) + + def test_calculate_num_params_from_pytree(self): + example_tree = [ + [1, 'a', object()], + (1, (2, 3), ()), + [1, {'k1': 2, 'k2': (3, 4)}, 5], + {'a': 2, 'b': (2, 3)}, + jnp.array([1, 2, 3]), + ] + self.assertEqual(max_utils.calculate_num_params_from_pytree(example_tree), 17) + # Model params + self.assertEqual(max_utils.calculate_num_params_from_pytree(self.params), 55) + + def test_init_train_state(self): + state = train_state.TrainState( + step=0, + apply_fn=self.model.apply, + params=self.params, + tx=None, # type: ignore + opt_state={} + ) + self.assertEqual(state.tx, None) + self.assertEqual(state.step, 0) + self.assertEqual(state.opt_state, {}) + self.assertEqual(state.apply_fn, self.model.apply) + self.assertEqual(max_utils.calculate_num_params_from_pytree(state.params), + max_utils.calculate_num_params_from_pytree(self.params)) + + + def test_init_decode_state(self): + decode_state = max_utils.init_decode_state( + self.model.apply, self.params + ) + self.assertEqual(decode_state.apply_fn, self.model.apply) + output = decode_state.apply_fn(self.params, self.input) + self.assertEqual(output.tolist(), self.output.tolist()) + self.assertEqual(decode_state.tx, None) + self.assertEqual(decode_state.opt_state, {}) + self.assertEqual(decode_state.step, 0) + self.assertEqual( + max_utils.calculate_num_params_from_pytree(decode_state.params), + max_utils.calculate_num_params_from_pytree(self.params) + ) + + def test_init_training_state(self): + state = max_utils.init_training_state(self.model.apply, self.params, self.tx) + self.assertEqual(state.apply_fn, self.model.apply) + self.assertEqual(state.tx, self.tx) + self.assertNotEqual(state.opt_state, {}) + self.assertEqual( + max_utils.calculate_num_params_from_pytree(state.params), + max_utils.calculate_num_params_from_pytree(self.params) + ) + +class MaxUtilsInitTransformerState(unittest.TestCase): + """Tests initialization of transformer states in max_utils.py""" + + def setUp(self): + pyconfig.initialize([None, "configs/base.yml"], enable_checkpointing=False) + self.config = pyconfig.config + devices_array = max_utils.create_device_mesh(self.config) + self.mesh = Mesh(devices_array, self.config.mesh_axes) + quant = quantizations.configure_quantization(self.config) + self.model = Transformer(self.config, mesh=self.mesh, quant=quant) + + def test_setup_decode_state(self): + rng = random.PRNGKey(0) + state, _ = max_utils.setup_decode_state( + self.model, self.config, rng, self.mesh, None) + self.assertEqual(state.tx, None) + self.assertEqual(state.opt_state, {}) + + def test_setup_initial_state(self): + rng = random.PRNGKey(0) + tx = optax.adam(learning_rate=0.001) + state, _, _ = max_utils.setup_initial_state( + self.model, None, tx, self.config, rng, self.mesh, None) + self.assertEqual(state.tx, tx) + self.assertNotEqual(state.opt_state, {}) + +class MaxUtilsT5XCrossEntropy(unittest.TestCase): + """Tests for the cross entropy functions in max_utils.py""" + def test_t5x_cross_entropy(self): + # Generate random targets and logits + key = jax.random.PRNGKey(0) + targets = jax.random.randint(key, shape=(48, 2048), + dtype=jax.numpy.int32, minval=1, maxval=10) + logits = jax.random.uniform(key, shape=(48, 2048, 4096), + dtype=jax.numpy.float32) + + # Calculate xent from optax implementation + optax_xent = optax.softmax_cross_entropy_with_integer_labels(logits, targets) + + # Calculate xent from custom T5X implementation + one_hot_targets = jax.nn.one_hot(targets, 4096) + t5x_xent, _ = max_utils.cross_entropy_with_logits(logits, one_hot_targets, 0.0) + t5x_xent = nn.with_logical_constraint(t5x_xent, ('activation_batch', 'activation_length')) + + # Compare results + self.assertTrue(jax.numpy.allclose(optax_xent, t5x_xent, rtol=1e-05, atol=1e-08, equal_nan=False)) + +if __name__ == '__main__': + unittest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/model_test.py b/maxtext-setup/maxtext/MaxText/tests/model_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5ab89406e6c05327c87a48c9014579d0423b758d --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/model_test.py @@ -0,0 +1,133 @@ +# Copyright 2023 Google LLC +# +# 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. + +import sys +import unittest + +import common_types + +from flax.core import freeze +import jax +import jax.numpy as jnp +import max_utils +import numpy as np +import pytest + +import pyconfig + +from layers import models +from layers import quantizations + +Mesh = jax.sharding.Mesh +MAX_PREFILL_PREDICT_LENGTH = 4 + +class TestModel(unittest.TestCase): + """Test the Whole Model """ + def setUp(self): + super().setUp() + pyconfig.initialize([sys.argv[0], 'configs/base.yml'], per_device_batch_size = 1.0, run_name='test', + enable_checkpointing=False, base_num_decoder_layers=2, attention="dot_product", + max_target_length=16, base_emb_dim=256, base_num_query_heads=2, base_num_kv_heads=2, max_prefill_predict_length=4) + self.cfg = pyconfig.config + self.rng = jax.random.PRNGKey(0) + + def get_data(self): + s = (self.cfg.global_batch_size_to_train_on, self.cfg.max_target_length) + ids = jax.random.randint( + self.rng, + s, + 0, + self.cfg.vocab_size + ) + + decoder_segment_ids = jax.numpy.zeros(s) + common_types.DECODING_ACTIVE_SEQUENCE_INDICATOR + decoder_positions = jnp.stack([ + jnp.arange(self.cfg.max_target_length, dtype=jnp.int32) + for _ in range(self.cfg.global_batch_size_to_train_on) + ]) + + return ids, decoder_segment_ids, decoder_positions + + @pytest.mark.tpu + def test_train_vs_prefill_and_autoregress(self): + PREFILL_RANGE = MAX_PREFILL_PREDICT_LENGTH + + devices_array = max_utils.create_device_mesh(self.cfg) + mesh = Mesh(devices_array, self.cfg.mesh_axes) + quant = quantizations.configure_quantization(self.cfg) + model = models.Transformer(config = self.cfg, mesh = mesh, quant=quant) + + ids, decoder_segment_ids, decoder_positions = self.get_data() + + transformer_vars = model.init( + {'params': self.rng, 'aqt': self.rng}, + ids, + decoder_positions, + decoder_segment_ids, + enable_dropout=False + ) + + full_train_logits = model.apply( + transformer_vars, + ids, + decoder_positions, + decoder_segment_ids, + enable_dropout=False, + model_mode = common_types.MODEL_MODE_TRAIN, + rngs={'aqt': self.rng} + ) + + partial_prefill_logits, partial_cache = model.apply( + transformer_vars, + ids[:, :PREFILL_RANGE], + decoder_positions[:, :PREFILL_RANGE], + decoder_segment_ids=decoder_segment_ids[:, :PREFILL_RANGE], + enable_dropout=False, + model_mode = common_types.MODEL_MODE_PREFILL, + rngs={'aqt': self.rng}, + mutable=["cache"], + ) + + self.assertTrue( + jax.numpy.allclose( + full_train_logits[:,:PREFILL_RANGE,:], partial_prefill_logits, rtol=1e-01, atol=1e-01, equal_nan=False + ) + ) + + for idx in range(PREFILL_RANGE, self.cfg.max_target_length): + ids_idx = ids[:, idx:idx+1] + decoder_positions_idx = decoder_positions[:, idx:idx+1] + transformer_vars.update(partial_cache) + ar_logits, partial_cache = model.apply( + transformer_vars, + ids_idx, + decoder_positions_idx, + enable_dropout=False, + model_mode = common_types.MODEL_MODE_AUTOREGRESSIVE, + rngs={'aqt': self.rng}, + mutable=["cache"], + ) + + full_train_logits_idx = full_train_logits[:,idx:idx+1,:] + self.assertTrue( + full_train_logits_idx.shape == ar_logits.shape + ) + self.assertTrue( + jax.numpy.allclose( + full_train_logits_idx, ar_logits, rtol=1e-01, atol=1e-01, equal_nan=False + ) + ) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/maxtext-setup/maxtext/MaxText/tests/multihost_dataloading_test.py b/maxtext-setup/maxtext/MaxText/tests/multihost_dataloading_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e620c2e1ed06e9b84283034d0d758e0d931efe48 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/multihost_dataloading_test.py @@ -0,0 +1,70 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=missing-module-docstring, missing-function-docstring +import sys +import numpy as np +import jax +from jax.sharding import Mesh +from jax.experimental import mesh_utils +from jax.sharding import PartitionSpec + +import tensorflow as tf +import unittest +import pytest + +import pyconfig +import multihost_dataloading + + +class MultihostDataloadingTest(unittest.TestCase): + + def setUp(self): + super().setUp() + batch_size = 4 + pyconfig.initialize([sys.argv[0], 'configs/base.yml'], per_device_batch_size=1, run_name='test', mesh_axes = ['data'], + logical_axis_rules = [['batch', 'data']], + data_sharding = ['data'], + base_output_directory = "gs://max-experiments/", + dataset_path = "gs://maxtext-dataset/", + enable_checkpointing=False) + config = pyconfig.config + global_data_shape = PartitionSpec(batch_size, config.max_target_length) + data_sharding = ('data',) + mesh_shape_1d = (len(jax.devices()),) + self.mesh = Mesh(mesh_utils.create_device_mesh(mesh_shape_1d), config.mesh_axes) + data_axes = PartitionSpec('data',) + # creating 2 batches of data + global_data = np.arange(np.prod(global_data_shape)*2).reshape((batch_size * 2, config.max_target_length)) + + dataset = tf.data.Dataset.from_tensor_slices(global_data) + dataset = dataset.repeat() + dataset = dataset.batch(batch_size) + self.multihost_gen = ( + multihost_dataloading.MultiHostDataLoadIterator( + dataset, self.mesh + ) + ) + + @pytest.mark.tpu + def test_batch_sharded_data_pipeline(self): + first_batch = next(self.multihost_gen) + sec_batch = next(self.multihost_gen) + self.assertTrue(not np.array_equal(first_batch, sec_batch, equal_nan=True)) + + +if __name__ == '__main__': + unittest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/profiler_test.py b/maxtext-setup/maxtext/MaxText/tests/profiler_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0950730087e4c096314b8cf96e01bea2c0cd3ea3 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/profiler_test.py @@ -0,0 +1,86 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Profiler tests for TPUs.""" +import glob +import json +import os +import unittest + +from tensorboard_plugin_profile.convert import raw_to_tool_data + + +class TpuJAXTest(unittest.TestCase): + + """Test for profile collected with JAX.""" + + def _get_session_snapshot(self): + """Gets a session snapshot of current session. assume only one session.""" + profile_plugin_root ="tensorboard/plugins/profile" + # The session exists under a director whose name is time-dependent. + profile_session_glob = os.path.join(profile_plugin_root, '*', '*.xplane.pb') + return glob.glob(profile_session_glob) + + def test_xplane_is_present(self): + files = self._get_session_snapshot() + self.assertEqual(len(files), 1) + + def test_overview_page(self): + xspace_filenames = self._get_session_snapshot() + result, _ = raw_to_tool_data.xspace_to_tool_data(xspace_filenames, + 'overview_page^', {}) + result = json.loads(result) + run_environment = result[2] + self.assertEqual(run_environment['p']['host_count'], '1') + self.assertRegex(run_environment['p']['device_type'], 'TPU.*') + + def test_op_profile(self): + xspace_filenames = self._get_session_snapshot() + result, _ = raw_to_tool_data.xspace_to_tool_data( + xspace_filenames, 'op_profile^', {} + ) + result = json.loads(result) + self.assertIn('byCategory', result) + self.assertIn('metrics', result['byCategory']) + overall_metrics = result['byCategory']['metrics'] + self.assertIn('flops', overall_metrics) + self.assertIn('bandwidthUtils', overall_metrics) + self.assertGreater(overall_metrics['flops'], 0) + + def test_device_trace_contains_threads(self): + xspace_filenames = self._get_session_snapshot() + result, _ = raw_to_tool_data.xspace_to_tool_data( + xspace_filenames, 'trace_viewer^', {} + ) + result = json.loads(result) + thread_names = [] + for event in result['traceEvents']: + if 'name' in event and event['name'] == 'thread_name': + thread_names.append((event['args']['name'])) + expected_threads = [ + 'TensorFlow Name Scope', + 'TensorFlow Ops', + 'XLA Modules', + 'XLA Ops', + 'XLA TraceMe', + 'Steps', + ] + # Ensure that thread_names contains at least all expected threads. + self.assertEqual(set(expected_threads)-set(thread_names), set()) + + +if __name__ == '__main__': + unittest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/quantizations_test.py b/maxtext-setup/maxtext/MaxText/tests/quantizations_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7f35ffb0f1e9be2b15e092c8a00660b93e755975 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/quantizations_test.py @@ -0,0 +1,124 @@ +""" + Copyright 2024 Google LLC + + 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. + """ + +""" Tests for the quantizations """ +from jax import numpy as jnp +from jax import random, lax +from flax import linen as nn +import numpy as np +import pyconfig +from layers import quantizations +import unittest + +class QuantTestModule(nn.Module): + """Test module for einsum.""" + quantization: quantizations.AqtQuantization + + @nn.compact + def __call__(self, inputs): + identity = jnp.identity(2, dtype=inputs.dtype) + einsum = jnp.einsum + dot_general = lax.dot_general + if self.quantization: + einsum = self.quantization.einsum() + dot_general_cls = self.quantization.dot_general_cls() + dot_general = dot_general_cls() + res_einsum = einsum('bc,ab->ac', inputs, identity) + res_dg = dot_general(inputs, inputs, (((), ()), ((), ())), precision=None) + return res_einsum, res_dg + +def _configure_quantization(quant_str="", mode_str='train'): + pyconfig.initialize([None, "configs/base.yml"], enable_checkpointing=False, quantization=quant_str) + config = pyconfig.config + quant = quantizations.configure_quantization(config, mode_str) + return quant + +def _apply(quant_str=""): + quant = _configure_quantization(quant_str) + test_module = QuantTestModule(quant) + rng = random.PRNGKey(0) + variables = test_module.init({'params': rng}, jnp.ones((2, 2))) + inputs = jnp.ones((2, 2)) + res_einsum, res_dg = test_module.apply(variables, inputs, rngs={'params': random.PRNGKey(0)}) + return inputs, res_einsum, res_dg + + +class QuantizationTest(unittest.TestCase): + """Tests for quantization.""" + + def test_in_quant_mode(self): + quant = _configure_quantization(quant_str="int8", mode_str='convert') + self.assertTrue(quantizations.in_convert_mode(quant)) + self.assertFalse(quantizations.in_serve_mode(quant)) + + + def test_configure_quantization_is_null(self): + for quant_mode in ["train", "serve", "convert"]: + quant = _configure_quantization(quant_str="", mode_str=quant_mode) + self.assertEqual(quant, None) + + def test_configure_quantization_is_int8(self): + for quant_mode in ["train", "serve", "convert"]: + quant = _configure_quantization(quant_str="int8", mode_str=quant_mode) + self.assertNotEqual(quant, None) + + def test_aqt_quantization(self): + # Without quantization + inputs, res_einsum, res_dg = _apply() + self.assertTrue(jnp.array_equal(inputs, res_einsum)) + self.assertEqual(res_einsum.dtype, np.dtype(np.float32)) + self.assertTrue(jnp.array_equal(inputs, res_dg[0][0])) + self.assertEqual(res_dg.dtype, np.dtype(np.float32)) + + # With int8 quantization + inputs, res_einsum, res_dg = _apply(quant_str="int8") + self.assertTrue(jnp.greater(jnp.max(inputs), jnp.max(res_einsum))) + self.assertEqual(res_einsum.dtype, np.dtype(np.float32)) + self.assertTrue(jnp.greater(jnp.max(inputs), jnp.max(res_dg[0][0]))) + #self.assertEqual(res_dg.dtype, np.dtype(np.float32)) + + def test_remove_quantized_params(self): + _params = { + 'decoder': { + 'decoder_norm': {'scale': 1.0}, + 'layers': { + 'mlp': {'wi_0': {'kernel': 1.0}, 'wi_1': {'kernel': 1.0}, 'wo': {'kernel': 1.0}}, + 'self_attention': {'key': {'kernel': 1.0},}}, + 'logits_dense': {'kernel': 1.0}}, + } + _aqt_vars = { + 'decoder': { + 'layers': { + 'mlp': { + 'wi_0': {'AqtDotGeneral_0': {'qrhs': {'scale': 1.0, '_value': 1.0 }}}, + 'wi_1': {'AqtDotGeneral_0': {'qrhs': {'scale': 1.0, '_value': 1.0 }}}, + 'wo': {'AqtDotGeneral_0': {'qrhs': {'scale': 1.0, '_value': 1.0 }}} + }, + 'self_attention': {'key': {'AqtDotGeneral_0': {'qrhs': {'scale': 1.0, '_value': 1.0}},}}}} + } + _expected = { + 'decoder': { + 'decoder_norm': {'scale': 1.0}, + 'layers': { + 'mlp': {'wi_0': {'kernel': {}}, 'wi_1': {'kernel': {}}, 'wo': {'kernel': {}}}, + 'self_attention': {'key': {'kernel': {}},}}, + 'logits_dense': {'kernel': 1.0},} + } + result = quantizations.remove_quantized_params(_params, _aqt_vars) + self.assertEqual(_expected, result) + +if __name__ == '__main__': + unittest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/tfds_data_processing_test.py b/maxtext-setup/maxtext/MaxText/tests/tfds_data_processing_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3db379e372ba7bfc25aa150ee812cb70aee2c505 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/tfds_data_processing_test.py @@ -0,0 +1,142 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=missing-module-docstring, missing-function-docstring +import os +import sys +import jax +from jax.sharding import Mesh +from jax.experimental import mesh_utils + +import unittest +import tensorflow as tf +import tensorflow_datasets as tfds + +import pyconfig +from input_pipeline import _tfds_data_processing +from input_pipeline import input_pipeline_interface + +class TfdsDataProcessingTest(unittest.TestCase): + + def setUp(self): + super().setUp() + pyconfig.initialize([sys.argv[0], 'configs/base.yml'], per_device_batch_size=1, run_name='test', mesh_axes = ['data'], + logical_axis_rules = [['batch', 'data']], + data_sharding = ['data'], + base_output_directory = "gs://max-experiments/", + dataset_path = "gs://maxtext-dataset/", + tokenizer_path = "../assets/tokenizer", + enable_checkpointing=False) + os.environ["TFDS_DATA_DIR"] = pyconfig.config.dataset_path + self.config = pyconfig.config + self.mesh_shape_1d = (len(jax.devices()),) + self.mesh = Mesh(mesh_utils.create_device_mesh(self.mesh_shape_1d), self.config.mesh_axes) + self.read_config = tfds.ReadConfig( + shuffle_seed = self.config.data_shuffle_seed, + ) + self.read_config.add_tfds_id = True + + self.train_ds, self.eval_ds = self._get_datasets() + self.train_iter, self.eval_iter, self.predict_iter = self._get_preprocessed_datasets() + + def _get_datasets(self): + print("Sharding dataset in ", jax.process_count(), " shards") + train_ds, eval_ds = _tfds_data_processing.get_datasets( + config=self.config, read_config = self.read_config) + return train_ds, eval_ds + + def _get_preprocessed_datasets(self): + mesh_shape_1d = (len(jax.devices()),) + mesh = Mesh(mesh_utils.create_device_mesh(mesh_shape_1d), self.config.mesh_axes) + sp_tokenizer = input_pipeline_interface.get_tokenizer(self.config.tokenizer_path) + train_iter, eval_iter, test_iter = _tfds_data_processing.preprocess_dataset( + self.config, + mesh, + self.train_ds, self.eval_ds, sp_tokenizer) + return train_iter, eval_iter, test_iter + + def test_train_ds(self): + expected_shape = [jax.device_count(), self.config.max_target_length] + # For training we pack multiple short examples in one example. + # *_position and *_segmentation indicate the boundaries. + batch = next(self.train_iter) + self.assertEqual({k: list(v.shape) for k, v in batch.items()}, { + 'inputs': expected_shape, + 'inputs_position': expected_shape, + 'inputs_segmentation': expected_shape, + 'targets': expected_shape, + 'targets_position': expected_shape, + 'targets_segmentation': expected_shape, + }) + + + def test_eval_ds(self): + expected_shape = [jax.device_count(), self.config.max_target_length] + batch = next(self.eval_iter) + self.assertEqual({k: list(v.shape) for k, v in batch.items()}, { + 'inputs': expected_shape, + 'targets': expected_shape, + }) + + + def test_predict_ds(self): + expected_shape = [jax.device_count(), self.config.max_target_length] + batch = next(self.predict_iter) + self.assertEqual({k: list(v.shape) for k, v in batch.items()}, { + 'inputs': expected_shape, + 'targets': expected_shape, + }) + + + def test_ds_determinism(self): + train_ds1 = self.train_ds.batch(64) + train_ds1 = next(train_ds1.as_numpy_iterator()) + # reset the dataset loading + train_ds, _ = self._get_datasets() + train_ds = train_ds.batch(64) + train_ds2 = next(train_ds.as_numpy_iterator()) + + self.assertCountEqual(train_ds1['tfds_id'], train_ds2['tfds_id']) + + + def test_batch_determinism(self): + batch1 = next(self.train_iter) + self.train_ds, _ = self._get_datasets() + train_iter2, _, _= self._get_preprocessed_datasets() + batch2 = next(train_iter2) + self.assertTrue(tf.reduce_all(tf.equal(batch1['inputs'], batch2['inputs']))) + self.assertTrue(tf.reduce_all(tf.equal(batch1['targets'], batch2['targets']))) + self.assertTrue(tf.reduce_all(tf.equal(batch1['inputs_segmentation'], batch2['inputs_segmentation']))) + self.assertTrue(tf.reduce_all(tf.equal(batch1['targets_segmentation'], batch2['targets_segmentation']))) + self.assertTrue(tf.reduce_all(tf.equal(batch1['inputs_position'], batch2['inputs_position']))) + self.assertTrue(tf.reduce_all(tf.equal(batch1['targets_position'], batch2['targets_position']))) + + def test_for_loop_repeatable(self): + def get_first_batch(iterator): + batch = None + for batch in iterator: + break + return batch + + eval_batch1 = get_first_batch(self.eval_iter) + eval_batch2 = get_first_batch(self.eval_iter) + self.assertTrue((eval_batch1['inputs']==eval_batch2['inputs']).all()) + self.assertTrue((eval_batch1['targets']==eval_batch2['targets']).all()) + + +if __name__ == '__main__': + unittest.main() + diff --git a/maxtext-setup/maxtext/MaxText/tests/tokenizer_test.py b/maxtext-setup/maxtext/MaxText/tests/tokenizer_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6797f6ee31186efdb55733e26421363fbf8dd93a --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/tokenizer_test.py @@ -0,0 +1,70 @@ +""" + Copyright 2023 Google LLC + + 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. +""" + +""" Tests for tokenizer +""" + +import numpy as np +import train_tokenizer +import tokenizer +import unittest +import tensorflow_datasets as tfds +import os + + +class TokenizerTest(unittest.TestCase): + """Tests for train_tokenizer.py""" + + @classmethod + def setUpClass(cls): + dataset_name = 'c4/en:3.0.1' + dataset_path = 'gs://maxtext-dataset' + cls.vocab_size = 32_768 + cls.max_corpus_chars = 10_000_000 + assets_path = 'tests' + vocab_model_name = 'test_tokenizer' + cls.tokenizer_path = os.path.join(assets_path, vocab_model_name) + os.environ["TFDS_DATA_DIR"] = dataset_path + read_config = tfds.ReadConfig( + shuffle_seed = 0, + ) + train_ds_builder = tfds.builder(dataset_name) + cls.dataset = train_ds_builder.as_dataset(split='train', read_config=read_config, shuffle_files=True) + train_tokenizer.train_tokenizer(cls.dataset, + assets_path=assets_path, + vocab_path=cls.tokenizer_path, + vocab_size=cls.vocab_size, + max_corpus_chars=cls.max_corpus_chars) + + @classmethod + def tearDownClass(cls): + os.remove(cls.tokenizer_path) + + def test_tokenize(self): + source_tokenizer = tokenizer.load_tokenizer('../assets/tokenizer') + test_tokenizer = tokenizer.load_tokenizer(self.tokenizer_path) + text = 'This is a test' + self.assertTrue((np.asarray(source_tokenizer.tokenize(text)) & np.asarray(test_tokenizer.tokenize(text))).all()) + + def test_detokenize(self): + source_tokenizer = tokenizer.load_tokenizer('../assets/tokenizer') + test_tokenizer = tokenizer.load_tokenizer(self.tokenizer_path) + tokens = [66,12,10,698,2] + self.assertEqual(np.asarray(source_tokenizer.detokenize(tokens)),np.asarray(test_tokenizer.detokenize(tokens))) + + +if __name__ == '__main__': + unittest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/train_compile_test.py b/maxtext-setup/maxtext/MaxText/tests/train_compile_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf46e753eeb848da45d667376b551495dca48bd --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/train_compile_test.py @@ -0,0 +1,98 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Tests for the common Max Utils """ +import unittest +import pytest +from train_compile import main as train_compile_main +from train import main as train_main + + +class TrainCompile(unittest.TestCase): + """Tests for the Ahead of Time Compilation functionality, train_compile.py""" + + @pytest.mark.tpu + def test_save_compiled_v4(self): + compiled_trainstep_file='/tmp/test_compiled_v4.pickle' + train_compile_main((None, "configs/base.yml", f"compiled_trainstep_file={compiled_trainstep_file}", + "compile_topology=v4-8", "compile_topology_num_slices=1", "base_emb_dim=256", "base_mlp_dim=256", + "base_num_decoder_layers=2")) + + @pytest.mark.tpu + def test_save_compiled_v5e(self): + compiled_trainstep_file='/tmp/test_compiled_v5e.pickle' + train_compile_main((None, "configs/base.yml", f"compiled_trainstep_file={compiled_trainstep_file}", + "compile_topology=v5e-16", "compile_topology_num_slices=1", "base_emb_dim=256", "base_mlp_dim=256", + "base_num_decoder_layers=2")) + + @pytest.mark.tpu + def test_minimal_offloaded_v5e(self): + compiled_trainstep_file='/tmp/test_compiled_v5e_offload.pickle' + train_compile_main((None, "configs/base.yml", f"compiled_trainstep_file={compiled_trainstep_file}", + "compile_topology=v5e-256", "compile_topology_num_slices=1", "per_device_batch_size=1", "ici_fsdp_parallelism=16", + "ici_tensor_parallelism=16", "max_target_length=2048", + "fused_qkv=true", "fused_mlp=true", "remat_policy=minimal_offloaded", + "use_iota_embed=true", "global_parameter_scale=128")) + + @pytest.mark.tpu + def test_save_compiled_v5p_two_slices(self): + compiled_trainstep_file='/tmp/test_compiled_v5p_two_slices.pickle' + train_compile_main((None, "configs/base.yml", f"compiled_trainstep_file={compiled_trainstep_file}", + "compile_topology=v5p-8", "compile_topology_num_slices=2", "base_emb_dim=256", "base_mlp_dim=256", + "base_num_decoder_layers=2")) + + @pytest.mark.tpu + def test_sequence_parallelism(self): + compiled_trainstep_file='/tmp/test_compiled.pickle' + train_compile_main((None, "configs/base.yml", f"compiled_trainstep_file={compiled_trainstep_file}", + "compile_topology=v5e-256", "use_iota_embed=true", "compile_topology_num_slices=1", + "ici_sequence_parallelism=16", "global_parameter_scale=32", "per_device_batch_size=0.0625", "max_target_length=65536")) + + @pytest.mark.tpu + def test_remat_save_dot_except_mlpwi(self): + compiled_trainstep_file='/tmp/test_remat_save_dot_except_mlpwi.pickle' + train_compile_main((None, "configs/base.yml", f"compiled_trainstep_file={compiled_trainstep_file}", + "compile_topology=v5e-256", "compile_topology_num_slices=1", "per_device_batch_size=0.125", "ici_fsdp_parallelism=16", + "ici_tensor_parallelism=16", "max_target_length=2048", + "fused_qkv=true", "fused_mlp=true", "remat_policy=save_dot_except_mlpwi", + "use_iota_embed=true", "global_parameter_scale=128")) + + @pytest.mark.tpu + def test_remat_save_dot_except_mlp(self): + compiled_trainstep_file='/tmp/test_remat_save_dot_except_mlp.pickle' + train_compile_main((None, "configs/base.yml", f"compiled_trainstep_file={compiled_trainstep_file}", + "compile_topology=v5e-256", "compile_topology_num_slices=1", "per_device_batch_size=0.25", "ici_fsdp_parallelism=16", + "ici_tensor_parallelism=16", "max_target_length=2048", + "fused_qkv=true", "fused_mlp=true", "remat_policy=save_dot_except_mlp", + "use_iota_embed=true", "global_parameter_scale=128")) + + @pytest.mark.tpu + def test_remat_save_qkv_proj(self): + compiled_trainstep_file='/tmp/test_remat_save_qkv_proj.pickle' + train_compile_main((None, "configs/base.yml", f"compiled_trainstep_file={compiled_trainstep_file}", + "compile_topology=v5e-256", "compile_topology_num_slices=1", "per_device_batch_size=0.375", "ici_fsdp_parallelism=16", + "ici_tensor_parallelism=16", "max_target_length=2048", + "fused_qkv=true", "fused_mlp=true", "remat_policy=save_qkv_proj", + "use_iota_embed=true", "global_parameter_scale=128")) + + @pytest.mark.tpu + def test_remat_full(self): + compiled_trainstep_file='/tmp/test_remat_full.pickle' + train_compile_main((None, "configs/base.yml", f"compiled_trainstep_file={compiled_trainstep_file}", + "compile_topology=v5e-256", "compile_topology_num_slices=1", "per_device_batch_size=1", "ici_fsdp_parallelism=16", + "ici_tensor_parallelism=16", "max_target_length=2048", + "fused_qkv=true", "fused_mlp=true", "remat_policy=full", + "use_iota_embed=true", "global_parameter_scale=128")) \ No newline at end of file diff --git a/maxtext-setup/maxtext/MaxText/tests/train_gpu_smoke_test.py b/maxtext-setup/maxtext/MaxText/tests/train_gpu_smoke_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f9df3a55a71094bc758243e58689bddf11d7ca --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/train_gpu_smoke_test.py @@ -0,0 +1,39 @@ +"""Copyright 2024 Google LLC + +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. +""" + +""" Smoke test """ +import os +import unittest +from absl.testing import absltest +from train import main as train_main + + +class Train(unittest.TestCase): + """Smoke test for GPUs.""" + + def test_tiny_config(self): + test_tmpdir = os.environ.get("TEST_TMPDIR") + train_main([ + None, + "third_party/py/maxtext/configs/gpu_smoke_test.yml", + f"base_output_directory=gs://runner-maxtext-logs", + "run_name=runner_test", + r"dataset_path=gs://maxtext-dataset", + "enable_checkpointing=False", + ]) + + +if __name__ == "__main__": + absltest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/train_int8_smoke_test.py b/maxtext-setup/maxtext/MaxText/tests/train_int8_smoke_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5efc5ebeb34497e9d01dafd621f04cf8c8b79658 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/train_int8_smoke_test.py @@ -0,0 +1,37 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Smoke test for int8""" +import os +import unittest +from train import main as train_main +from absl.testing import absltest + +class Train(unittest.TestCase): + """Smoke test for int8 G3 only""" + + def test_tiny_config(self): + test_tmpdir = os.environ.get("TEST_TMPDIR") + train_main([None, "third_party/py/maxtext/configs/base.yml", + f"base_output_directory=gs://runner-maxtext-logs", "run_name=runner_test", + r"dataset_path=gs://maxtext-dataset", + "base_emb_dim=8", "base_num_query_heads=4", "base_num_kv_heads=4", "base_mlp_dim=32", + "base_num_decoder_layers=8", "head_dim=128", "per_device_batch_size=2", + "max_target_length=1024", "dataset_type=synthetic", "steps=10", + "enable_checkpointing=False", "quantization=int8"]) + +if __name__ == '__main__': + absltest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/train_smoke_test.py b/maxtext-setup/maxtext/MaxText/tests/train_smoke_test.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd41fb339c06750df3f4b1b9e66b5d37e65b807 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/train_smoke_test.py @@ -0,0 +1,37 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Smoke test """ +import os +import unittest +from train import main as train_main +from absl.testing import absltest + +class Train(unittest.TestCase): + """Smoke test G3 only""" + + def test_tiny_config(self): + test_tmpdir = os.environ.get("TEST_TMPDIR") + train_main([None, "third_party/py/maxtext/configs/base.yml", + f"base_output_directory=gs://runner-maxtext-logs", "run_name=runner_test", + r"dataset_path=gs://maxtext-dataset", + "base_emb_dim=8", "base_num_query_heads=4", "base_num_kv_heads=4", "base_mlp_dim=32", + "base_num_decoder_layers=8", "head_dim=128", "per_device_batch_size=2", + "max_target_length=1024", "dataset_type=synthetic", "steps=10", + "enable_checkpointing=False"]) + +if __name__ == '__main__': + absltest.main() diff --git a/maxtext-setup/maxtext/MaxText/tests/weight_dtypes_test.py b/maxtext-setup/maxtext/MaxText/tests/weight_dtypes_test.py new file mode 100644 index 0000000000000000000000000000000000000000..49829d43c309701403204bc22b692533477de498 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tests/weight_dtypes_test.py @@ -0,0 +1,66 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Test that all weights are expected dtype (default float32) """ +import unittest +from absl.testing import absltest + +import pyconfig + +import optimizers +from layers import models +from layers import quantizations +import max_utils +import jax +from jax.sharding import Mesh +import jax.numpy as jnp + +Transformer = models.Transformer + +class WeightDtypes(unittest.TestCase): + """Test that all weights are expected dtype (default float32) """ + + def get_weights(self, argv): + """ Gets model weights """ + + # Setup necessary inputs to build a model state + pyconfig.initialize(argv) + config = pyconfig.config + quant = quantizations.configure_quantization(config) + devices_array = max_utils.create_device_mesh(config) + mesh = Mesh(devices_array, config.mesh_axes) + model = Transformer(config, mesh, quant=quant) + learning_rate_schedule = max_utils.create_learning_rate_schedule(config) + tx = optimizers.get_optimizer(config, learning_rate_schedule) + _, example_rng = jax.random.split(jax.random.PRNGKey(0), 2) + + abstract_state, _ , _ = max_utils.get_abstract_state(model, tx, config, example_rng, mesh) + return abstract_state.params + + def assert_weights_are_dtype(self, weights, expected_dtype): + jax.tree_util.tree_map_with_path(lambda x,y: self.assertEqual(y.dtype, expected_dtype), weights) + + def test_default_float32(self): + argv = [None, "configs/base.yml", "enable_checkpointing=False"] + weights = self.get_weights(argv) + self.assert_weights_are_dtype(weights, jnp.float32) + + def test_set_bf16(self): + argv = [None, "configs/base.yml", "enable_checkpointing=False", "weight_dtype=bfloat16"] + weights = self.get_weights(argv) + self.assert_weights_are_dtype(weights, jnp.bfloat16) + + diff --git a/maxtext-setup/maxtext/MaxText/tokenizer.py b/maxtext-setup/maxtext/MaxText/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..9e29b1e6825fe7aa723f9568be03c510977468d1 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/tokenizer.py @@ -0,0 +1,64 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +"""Provides op for tokenizing a dataset.""" + +from typing import Any, Dict, Iterable + +import dataclasses +from absl import logging +import tensorflow as tf +import tensorflow_text as tftxt + +import max_logging + + +Features = Dict[str, tf.Tensor] + + + +def _load_sentencepiece_tokenizer(tokenizer_path: str, + add_bos: bool = False, + add_eos: bool = True, + reverse: bool = False): + """Load a tf-text SentencePiece tokenizer from given model filepath.""" + max_logging.log(f"Tokenizer path: {tokenizer_path}") + with tf.io.gfile.GFile(tokenizer_path, 'rb') as model_fp: + sp_model = model_fp.read() + sp_tokenizer = tftxt.SentencepieceTokenizer( + model=sp_model, add_bos=add_bos, add_eos=add_eos, reverse=reverse) + return sp_tokenizer + +def load_tokenizer(tokenizer_path: str, add_bos=False, add_eos=True): + """Loads the tokenizer at `tokenizer_path` or trains a one from `dataset`.""" + try: + sp_tokenizer = _load_sentencepiece_tokenizer(tokenizer_path, add_bos, add_eos) + return sp_tokenizer + except (tf.errors.NotFoundError, tf.errors.InvalidArgumentError): + logging.info('SentencePiece vocab not found, Run train_tokenizer.py') + return None + + +@dataclasses.dataclass +class TokenizeOp: + + sp_tokenizer: Any + data_keys: Iterable[str] = ('inputs', 'targets') + + def __call__(self, features: Features) -> Features: + for k in self.data_keys: + features[k] = self.sp_tokenizer.tokenize(features[k]) + return features diff --git a/maxtext-setup/maxtext/MaxText/train.py b/maxtext-setup/maxtext/MaxText/train.py new file mode 100644 index 0000000000000000000000000000000000000000..73153d99d1fbaecba6919b92b30c449699a7dd27 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/train.py @@ -0,0 +1,492 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=g-bad-todo, abstract-method, consider-using-with, ungrouped-imports +"""Training loop and Decoding of the model.""" + +# Calling jax.device_count here prevents a "TPU platform already registered" error. +# See github.com/google/maxtext/issues/20 for more + +import datetime +import os +import sys +import functools + +from typing import Sequence +from absl import app +from flax import linen as nn +from flax.linen import partitioning as nn_partitioning +import grain.python as grain +import jax +import numpy as np +import optax +import orbax.checkpoint + +import checkpointing +import max_utils +import maxtext_utils +import max_logging +import optimizers +import pyconfig + +from input_pipeline.input_pipeline_interface import create_data_iterator_with_tokenizer +from layers import models + +import jax.numpy as jnp +from jax import random +from jax.sharding import Mesh + +from cloud_tpu_diagnostics import diagnostic +from cloud_tpu_diagnostics.configuration import debug_configuration +from cloud_tpu_diagnostics.configuration import diagnostic_configuration +from cloud_tpu_diagnostics.configuration import stack_trace_configuration + +from layers import quantizations + +Transformer = models.Transformer +EPS = 1e-8 + +def validate_train_config(config): + """ Validates the configuration is set correctly for train.py""" + + assert config.run_name, "Erroring out, need a real run_name" + if not config.dataset_path.startswith('gs://'): + max_logging.log("WARNING: 'dataset_path' might be pointing your local file system") + if not config.base_output_directory.startswith('gs://'): + max_logging.log("WARNING: 'base_output_directory' might be pointing your local file system") + assert config.steps > 0, "You must set steps or learning_rate_schedule_steps to a positive interger." + + + +def get_first_step(state): + with jax.spmd_mode('allow_all'): + return int(state.step) + + +def load_next_batch(train_iter, example_batch, config): + """Loads the next batch. Can keep reusing the same batch for performance reasons """ + + if config.reuse_example_batch and example_batch is not None: + return example_batch + else: + return next(train_iter) + +def record_scalar_metrics(metrics, step_time_delta, per_device_tflops, lr): + """Records scalar metrics to be written to tensorboard""" + metrics['scalar'].update({ + 'perf/step_time_seconds': step_time_delta.total_seconds() + }) + metrics['scalar'].update({ + 'perf/per_device_tflops' : per_device_tflops + }) + metrics['scalar'].update({ + 'perf/per_device_tflops_per_sec': + per_device_tflops / + step_time_delta.total_seconds() + }) + metrics['scalar'].update({'learning/current_learning_rate': lr }) + +_buffered_step = None +_buffered_metrics = None +def write_metrics(writer, local_metrics_file, running_gcs_metrics, metrics, step, config): + """Entry point for all metrics writing in Train's Main. + TODO: would be better as a Class in the future (that initialized all state!) + + To avoid introducing an unnecessary dependency, we "double buffer" -- we hold + onto the last metrics and step and only publish when we receive a new metrics and step. + The logic is that this ensures that Jax is able to queues train_steps and we + don't block when turning "lazy" Jax arrays into real Python numbers. + """ + global _buffered_step, _buffered_metrics + + if _buffered_metrics is not None: + if _buffered_step is None: + raise ValueError(f"When writing metrics, {_buffered_step=} was none") + write_metrics_to_tensorboard(writer, _buffered_metrics, _buffered_step, config) + + if config.metrics_file: + max_utils.write_metrics_locally(_buffered_metrics, _buffered_step, config, local_metrics_file) + + if config.gcs_metrics and jax.process_index() == 0: + running_gcs_metrics = max_utils.write_metrics_for_gcs(_buffered_metrics, _buffered_step, config, running_gcs_metrics) + + _buffered_step = step + _buffered_metrics = metrics + +def write_metrics_to_tensorboard(writer, metrics, step, config): + """ Writes metrics to tensorboard""" + with jax.spmd_mode('allow_all'): + if jax.process_index() == 0: + for metric_name in metrics.get("scalar",[]): + writer.add_scalar(metric_name, np.array(metrics["scalar"][metric_name]), step) + for metric_name in metrics.get("scalars",[]): + writer.add_scalars(metric_name, metrics["scalars"][metric_name], step) + + full_log = step % config.log_period == 0 + + max_logging.log(f"completed step: {step}, seconds: {metrics['scalar']['perf/step_time_seconds']:.3f}, " + f"TFLOP/s/device: {metrics['scalar']['perf/per_device_tflops_per_sec']:.3f}, " + f"loss: {metrics['scalar']['learning/loss']:.3f}") + + if full_log and jax.process_index() == 0: + max_logging.log( + f"To see full metrics 'tensorboard --logdir={config.tensorboard_dir}'" + ) + writer.flush() + +def save_checkpoint(checkpoint_manager, step, state, dataset_type='c4', data_iterator=None): + """Wrapper for saving checkpoint""" + if dataset_type == 'c4-array_record': + return checkpoint_manager.save( + step, + args=orbax.checkpoint.args.Composite( + items=orbax.checkpoint.args.PyTreeSave(item=state), + iter=grain.PyGrainCheckpointSave(data_iterator.local_iterator) + ) + ) + else: + return checkpoint_manager.save( + step, + args=orbax.checkpoint.args.Composite( + items=orbax.checkpoint.args.PyTreeSave(item=state) + )) + +# ----------------------------------------------------------------------------- +# Top-level Functions +# ----------------------------------------------------------------------------- + +def record_activation_metrics(output_metrics, intermediate_outputs, config): + """ Adds the activation metrics to the metrics dict""" + + if config.scan_layers: + metrics_dict = intermediate_outputs['intermediates']['decoder']['decoder'] + + for layer_num in range(config.num_decoder_layers): + output_metrics['scalar'][f'activ_fraction_zero/layer_{layer_num:03d}'] = \ + metrics_dict["activation_fraction_zero"][0][layer_num] + output_metrics['scalar'][f'activ_mean/layer_{layer_num:03d}'] = metrics_dict["activation_mean"][0][layer_num] + output_metrics['scalar'][f'activ_stdev/layer_{layer_num:03d}'] = metrics_dict["activation_stdev"][0][layer_num] + else: + for layer_num in range(config.num_decoder_layers): + layer = intermediate_outputs['intermediates']['decoder'][f'layers_{layer_num}'] + output_metrics['scalar'][f'activ_fraction_zero/layer_{layer_num:03d}'] = layer["activation_fraction_zero"][0] + output_metrics['scalar'][f'activ_mean/layer_{layer_num:03d}'] = layer["activation_mean"][0] + output_metrics['scalar'][f'activ_stdev/layer_{layer_num:03d}'] = layer["activation_stdev"][0] + +def loss_fn(model, config, data, dropout_rng, params, is_train=True): + '''loss_fn for both train and eval. + + Args: + model: A nn.Module + config: Config of parameters + data: Batch of data to apply to the model + dropout_rng: A key to use to generate rng for dropout + params: Model params + is_train: True for train_step and False for eval_step + + Returns: + loss: average loss + aux: a dictionary including intermediate_outputs, total_loss, and total_weights + ''' + # inputs, targets, segments, positions = apply_args + rng1, aqt_rng = jax.random.split(dropout_rng) + + # decimate proportion of data when per_device_batch_size<1 + if is_train: + for k, v in data.items(): + data[k] = v[:config.global_batch_size_to_train_on,:] + + logits, intermediate_outputs = model.apply({'params': params}, + data['inputs'], + data['inputs_position'], + decoder_segment_ids=data['inputs_segmentation'], + enable_dropout=config.enable_dropout if is_train else False, + rngs={'dropout': rng1, 'params': aqt_rng}, mutable='intermediates') + one_hot_targets = jax.nn.one_hot(data['targets'], config.vocab_size) + xent, _ = max_utils.cross_entropy_with_logits(logits, one_hot_targets, 0.0) + xent = nn.with_logical_constraint(xent, ('activation_batch', 'activation_length')) + # Mask out paddings at the end of each example. + xent = xent * (data['targets_segmentation'] != 0) + total_loss = jnp.sum(xent) + total_weights = jnp.sum(data['targets_segmentation'] != 0) + loss = total_loss / (total_weights + EPS) + aux = { + 'intermediate_outputs': intermediate_outputs, + 'total_loss': total_loss, + 'total_weights': total_weights, + } + return loss, aux + + +def train_step(model, config, state, data, dropout_rng): + """ + + Args: + model: A nn.Module + state: A pytree of the current state of the model + data: Batch of data to apply to the model + dropout_rng: A key to use to generate rng for dropout + + Returns: + new_state: Same format as state. + metrics: Dictionary of model metrics such as loss, training rate, etc. + rng2: A new rng key that can be used in future calls. + + """ + train_loss_fn = functools.partial(loss_fn, model, config, data, dropout_rng, is_train=True) + grad_fn = jax.value_and_grad(train_loss_fn, has_aux=True) + (loss, aux), raw_grads = grad_fn(state.params) + intermediate_outputs = aux['intermediate_outputs'] + + if config.gradient_clipping_threshold > 0: + grads, _ = optax.clip_by_global_norm(config.gradient_clipping_threshold).update(raw_grads, state, None) + else: + grads = raw_grads + new_state = state.apply_gradients(grads=grads) + metrics = {'scalar': {'learning/loss': loss, 'learning/grad_norm': max_utils.l2norm_pytree(grads), + 'learning/raw_grad_norm': max_utils.l2norm_pytree(raw_grads), + 'learning/param_norm': max_utils.l2norm_pytree(new_state.params)}, 'scalars': {}} + + if config.record_internal_nn_metrics: + record_activation_metrics(metrics, intermediate_outputs, config) + + return new_state, metrics + +def eval_step(model, config, state, data, dropout_rng): + """eval_step no backprop and new state compared with train_step.""" + eval_loss_fn = functools.partial(loss_fn, model, config, data, dropout_rng, is_train=False) + loss, aux = eval_loss_fn(state.params) + total_loss = aux['total_loss'] + total_weights = aux['total_weights'] + metrics = {'scalar': + {'evaluation/loss': loss, + 'evaluation/total_loss': total_loss, + 'evaluation/total_weights': total_weights}} + + return metrics + +def setup_mesh_and_model(config): + """ Set up the mesh and the model for training + + Args: + config + + Returns: + init_rng: RNG key + writer: Summary writer for tensorboard + checkpoint_manager: Orbax checkpointer + state_mesh_annotations: the mesh annotations for the train state + model: + mesh: + learning_rate_schedule: + tx: + """ + + init_rng = random.PRNGKey(config.init_weights_seed) + writer = max_utils.initialize_summary_writer(config) + checkpoint_manager = checkpointing.create_orbax_checkpoint_manager( + config.checkpoint_dir, + config.enable_checkpointing, + config.async_checkpointing, + config.checkpoint_period, + config.dataset_type, + ) + # Mesh definition + devices_array = max_utils.create_device_mesh(config) + mesh = Mesh(devices_array, config.mesh_axes) + + # Model and Optimizer definition + quant = quantizations.configure_quantization(config) + model = Transformer(config, mesh, quant=quant) + learning_rate_schedule = max_utils.create_learning_rate_schedule(config) + tx = optimizers.get_optimizer(config, learning_rate_schedule) + return init_rng, writer, checkpoint_manager, mesh, model, learning_rate_schedule, tx + +def setup_train_loop(config): + """ Set up prerequisites for the training loop - + checkpoint_manager, PRNG keys, Mesh, Model and optimizer. + Set up data iterator and tokenizer, initialize the model. + + Args: + config + + Returns: + init_rng: + writer: Summary writer for tensorboard + checkpoint_manager: Orbax checkpointer + state_mesh_annotations: the mesh annotations for the train state + model: + mesh: + learning_rate_schedule: + data_iterator: + state: the initialized train state + """ + init_rng, writer, checkpoint_manager, mesh, model, learning_rate_schedule, tx = setup_mesh_and_model(config) + data_iterator, eval_data_iterator, _ = create_data_iterator_with_tokenizer(config, mesh) + + state, state_mesh_annotations, data_iterator = max_utils.setup_training_state(model, data_iterator, + tx, config, init_rng, mesh, checkpoint_manager) + + return ( init_rng, writer, checkpoint_manager, state_mesh_annotations, model, + mesh, learning_rate_schedule, data_iterator, eval_data_iterator, state) + + +def train_loop(config, state=None): + """Main Training loop. + Args: + config: + state: + ckpt_path: + Returns: + """ + ( init_rng, writer, checkpoint_manager, state_mesh_annotations, model, + mesh, learning_rate_schedule, data_iterator, eval_data_iterator, state) = setup_train_loop(config) + # pylint: disable=line-too-long + functional_train, in_shard_train, out_shard_train, static_argnums_train, donate_argnums_train = maxtext_utils.get_functional_train_with_signature( + train_step, + mesh, + state_mesh_annotations, + model, + config + ) + + if eval_data_iterator: + # pylint: disable=line-too-long + functional_eval, in_shard_eval, out_shard_eval, static_argnums_eval, donate_argnums_eval = maxtext_utils.get_functional_eval_with_signature( + eval_step, + mesh, + state_mesh_annotations, + model, + config + ) + + + num_model_parameters = max_utils.calculate_num_params_from_pytree(state.params) + max_logging.log(f"number parameters: {num_model_parameters/1e9:.3f} billion") + per_device_tflops, _, _ = maxtext_utils.calculate_tflops_training_per_device(num_model_parameters, config) + + # Write train config params, num model params, and XLA flags to tensorboard + max_utils.add_text_to_summary_writer("num_model_parameters", str(num_model_parameters), writer) + max_utils.add_text_to_summary_writer("libtpu_init_args", os.environ["LIBTPU_INIT_ARGS"], writer) + max_utils.add_config_to_summary_writer(config, writer) + + # Define the compilation of functional_train, either by loading the compiled version or wrapping a new one in a jit + if config.compiled_trainstep_file != '': + print("Loading the compiled function...", flush=True) + # Need to pass train signature and state to determine i/o shapes of train_state for now. + p_train_step = maxtext_utils.load_compiled(config, functional_train, state) + print("Loaded compiled function!", flush=True) + else: + p_train_step = jax.jit( + functional_train, + in_shardings=in_shard_train, + out_shardings=out_shard_train, + static_argnums=static_argnums_train, + donate_argnums=donate_argnums_train) + + if eval_data_iterator: + p_eval_step = jax.jit( + functional_eval, + in_shardings=in_shard_eval, + out_shardings=out_shard_eval, + static_argnums=static_argnums_eval, + donate_argnums=donate_argnums_eval) + + local_metrics_file = open(config.metrics_file, 'a', encoding="utf8") if config.metrics_file else None + running_gcs_metrics = [] if config.gcs_metrics else None + + start_step = get_first_step(state) # this is the start_step for training + first_profiling_step = start_step + config.skip_first_n_steps_for_profiler + if config.enable_profiler and first_profiling_step >= config.steps: + raise ValueError("Profiling requested but initial profiling step set past training final step") + last_profiling_step = np.clip(first_profiling_step + config.profiler_steps - 1, first_profiling_step, config.steps - 1) + + example_batch = None + last_step_completion = datetime.datetime.now() + + for step in np.arange(start_step, config.steps): + if step == first_profiling_step: + max_utils.activate_profiler(config) + + with jax.profiler.StepTraceAnnotation("train", step_num=step): + example_batch = load_next_batch(data_iterator, example_batch, config) + nextrng = jax.jit(jax.random.fold_in)(init_rng, step) + with mesh, nn_partitioning.axis_rules(config.logical_axis_rules): + state, metrics = p_train_step( + state, example_batch, nextrng + ) + + new_time = datetime.datetime.now() + record_scalar_metrics(metrics, new_time - last_step_completion, per_device_tflops, learning_rate_schedule(step)) + last_step_completion = new_time + + if checkpoint_manager is not None: + if save_checkpoint(checkpoint_manager, step, state, config.dataset_type, data_iterator): + max_logging.log(f"saved a checkpoint at step {step}") + + # Upon preemption, exit when and only when all ongoing saves are complete. + if checkpoint_manager.reached_preemption(step): + checkpoint_manager.wait_until_finished() + sys.exit() + + write_metrics(writer, local_metrics_file, running_gcs_metrics, metrics, step, config) + + if config.eval_interval > 0 and step > start_step and step % config.eval_interval == 0: + assert eval_data_iterator + cumulative_eval_metrics = {"total_loss": 0., "total_weights": 0.} + for eval_batch in eval_data_iterator: + with mesh, nn_partitioning.axis_rules(config.logical_axis_rules): + eval_metrics = p_eval_step( + state, eval_batch, nextrng + ) + cumulative_eval_metrics['total_loss'] += float(eval_metrics['scalar']['evaluation/total_loss']) + cumulative_eval_metrics['total_weights'] += float(eval_metrics['scalar']['evaluation/total_weights']) + eval_loss = cumulative_eval_metrics['total_loss'] / (cumulative_eval_metrics['total_weights'] + EPS) + max_logging.log(f"average loss after {step=}: {eval_loss=}, total_weights={cumulative_eval_metrics['total_weights']}") + if eval_loss <= config.target_eval_loss: + max_logging.log(f"Early stop and exit loop after reaching {config.target_eval_loss=}") + max_utils.deactivate_profiler(config) + break + + if step == last_profiling_step: + max_utils.deactivate_profiler(config) + + if checkpoint_manager is not None: + checkpoint_manager.wait_until_finished() + write_metrics(writer, local_metrics_file, running_gcs_metrics, metrics, config.steps - 1, config) # final step metrics + max_utils.close_summary_writer(writer) + return state + +def main(argv: Sequence[str]) -> None: + jax.config.update('jax_default_prng_impl', 'unsafe_rbg') + os.environ["TF_CPP_MIN_LOG_LEVEL"] = "0" + os.environ["LIBTPU_INIT_ARGS"] = os.environ.get("LIBTPU_INIT_ARGS","") + " --xla_tpu_spmd_rng_bit_generator_unsafe=true" + pyconfig.initialize(argv) + config = pyconfig.config + validate_train_config(config) + os.environ["TFDS_DATA_DIR"] = config.dataset_path + debug_config = debug_configuration.DebugConfig( + stack_trace_config = stack_trace_configuration.StackTraceConfig( + collect_stack_trace = config.collect_stack_trace, + stack_trace_to_cloud = config.stack_trace_to_cloud, + stack_trace_interval_seconds = config.stack_trace_interval_seconds)) + diagnostic_config = diagnostic_configuration.DiagnosticConfig(debug_config) + with diagnostic.diagnose(diagnostic_config): + train_loop(config) + + +if __name__ == "__main__": + app.run(main) diff --git a/maxtext-setup/maxtext/MaxText/train_compile.py b/maxtext-setup/maxtext/MaxText/train_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..55384c13eb718827fae7f9c1122e5945a79aff2b --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/train_compile.py @@ -0,0 +1,163 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" +Save a Cross Ahead of Time Compiled (XAOT) version of train.py's train step +Generates shaped versions of state and data without ever constructing them, so its possible +to compile with target hardware (e.g. hundreds/thousands of chips), without using the hardware. +This helpfully detects if your configuration would run into memory problems (OOM) on the target hardware, +before having to use the target hardware - you will see the same OOM error message during this compilation +as you would on the target hardware. +""" + +import jax +from jax.experimental.topologies import get_topology_desc +from jax.sharding import Mesh +from jax.experimental.serialize_executable import serialize +from flax.linen import partitioning as nn_partitioning +import maxtext_utils +import optimizers +import max_utils +import pyconfig +from layers import models +from layers import quantizations +from typing import Sequence +from absl import app +import pickle +import accelerator_to_spec_map +import train +from input_pipeline import input_pipeline_interface + +Transformer = models.Transformer + + +def validate_config(config): + """ Validates the config is is setup correctly to compile, returning a useful error message if not. """ + assert config.compile_topology != '',\ + "You must pass your desired target hardware in compile_topology, e.g. compile_topology=v5e-256" + assert config.compile_topology_num_slices > 0,\ + "You must set compile_topology_num_slices to a positive integer" + +def get_topology_mesh(config): + """ Get the target hardware devices, and create configured mesh with them """ + target_hardware = accelerator_to_spec_map.get_system_characteristics(config.compile_topology) + topology_devices = get_topology_desc( + platform=target_hardware.platform, + topology_name=target_hardware.topology_name, + chip_config_name=target_hardware.chip_config_name, + chips_per_host_bounds=target_hardware.chips_per_host_bounds, + num_slices=config.compile_topology_num_slices, + ).devices + topology_device_mesh = max_utils.create_device_mesh(config, topology_devices) + topology_mesh = Mesh(topology_device_mesh, config.mesh_axes) + return topology_mesh + +def get_shaped_inputs(topology_mesh, config): + """ Get shaped abstractions of inputs to train_step: state, batch and rng """ + # Construct the model and optimizier to get shaped versions of the state + quant = quantizations.configure_quantization(config) + model = Transformer(config, topology_mesh, quant=quant) + # The learning_rate_schedule is baked into the compiled object. + learning_rate_schedule = max_utils.create_learning_rate_schedule(config) + tx = optimizers.get_optimizer(config, learning_rate_schedule) + + # Shaped RNG keys + _, example_rng = jax.random.split(jax.random.PRNGKey(0), 2) + shaped_rng = jax.ShapeDtypeStruct(example_rng.shape, example_rng.dtype) + + # Shaped state + abstract_state, state_mesh_annotations, _ = max_utils.get_abstract_state(model, tx, config, example_rng, topology_mesh) + + # Shaped batch + shaped_batch = input_pipeline_interface.get_shaped_batch(config) + + shaped_train_args = (abstract_state, shaped_batch, shaped_rng) + shaped_train_kwargs = {} + return shaped_train_args, shaped_train_kwargs, state_mesh_annotations, model + + +def jit_and_compile(func, func_input_args, func_input_kwargs, mesh, in_shardings, + out_shardings, static_argnums, donate_argnums, logical_axis_rules): + """ Jit, lower, and compile func.""" + with mesh, logical_axis_rules: + jitted = jax.jit( + func, + in_shardings=in_shardings, + out_shardings=out_shardings, + static_argnums=static_argnums, + donate_argnums=donate_argnums + ) + lowered = jitted.lower(*func_input_args, **func_input_kwargs) + compiled = lowered.compile() + return compiled + +def save_compiled(compiled, save_name): + """ Serialize and save the compiled function. """ + serialized, _, _ = serialize(compiled) + with open(save_name, "wb") as f: + pickle.dump(serialized, f) + +def main(argv: Sequence[str]) -> None: + jax.config.update('jax_default_prng_impl', 'unsafe_rbg') + print("Starting train_compile.py...", flush=True) + + # Parse and validate configuration + pyconfig.initialize(argv) + config = pyconfig.config + validate_config(config) + + # Create target mesh + topology_mesh = get_topology_mesh(config) + + # Get shaped inputs + shaped_train_args, shaped_train_kwargs, state_mesh_annotations, model = get_shaped_inputs(topology_mesh, config) + + # Get function to compile and shardings + func_to_compile, in_shard, out_shard, static_argnums, donate_argnums = maxtext_utils.get_functional_train_with_signature( + train.train_step, + topology_mesh, + state_mesh_annotations, + model, + config + ) + + # Compile + print("Jitting and compiling train step...", flush=True) + compiled = jit_and_compile( + func_to_compile, + shaped_train_args, + shaped_train_kwargs, + topology_mesh, + in_shard, + out_shard, + static_argnums, + donate_argnums, + nn_partitioning.axis_rules(config.logical_axis_rules) + ) + print("Jitting and compilation complete!", flush=True) + + # Serialize and save the compiled object + if config.compiled_trainstep_file != '': + print("Saving compiled object...") + save_compiled(compiled, config.compiled_trainstep_file) + print(f"Successfully saved compiled object as {config.compiled_trainstep_file}") + print("Finished train_compile.py successfully!", flush=True) + print(f"Cost analysis: {compiled.cost_analysis()}") + print(f"Memory analysis: {compiled.memory_analysis()}") + + +if __name__ == "__main__": + app.run(main) diff --git a/maxtext-setup/maxtext/MaxText/train_tokenizer.py b/maxtext-setup/maxtext/MaxText/train_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..dab4d99be6d11dea7b58fe1d70038143dc24de97 --- /dev/null +++ b/maxtext-setup/maxtext/MaxText/train_tokenizer.py @@ -0,0 +1,166 @@ +""" + Copyright 2023 Google LLC + 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. +""" + +""" Train tokenizer +Example usage: python3 MaxText/train_tokenizer.py --dataset_path=gs://maxtext-dataset --dataset_name=c4/en:3.0.1 +""" + +import os +import tempfile +import time +from typing import Tuple + +from absl import app +from absl import flags +from absl import logging +import jax +import tensorflow as tf +import tensorflow_datasets as tfds + +from sentencepiece import SentencePieceTrainer + +_DATASET_PATH = flags.DEFINE_string( + 'dataset_path', None, 'Path to the dataset', required=True +) +_DATASET_NAME = flags.DEFINE_string( + 'dataset_name', None, 'Name to the dataset', required=True +) +_VOCAB_SIZE = flags.DEFINE_integer('vocab_size', 32_768, 'Vocab size') +_MAX_CORPUS_CHARS = flags.DEFINE_integer( + 'max_corpus_chars', 10_000_000, 'Max corpus chars' +) +_ASSETS_PATH = flags.DEFINE_string( + 'assets_path', 'assets', 'Name to the dataset' +) +_VOCAB_MODEL_NAME = flags.DEFINE_string( + 'vocab_model_name', 'tokenizer', 'Name to the dataset' +) + +def _dump_chars_to_textfile( + dataset: tf.data.Dataset, + maxchars: int = int(1e7), + data_keys=('text',) +) -> Tuple[str, int]: + """Write part of a TFDS sentence dataset to lines in a text file. + Args: + dataset: tf.dataset containing string-data. + maxchars: int: approximate number of characters to save from dataset. + data_keys: Tuple[str]: what keys in dataset to dump from. + Returns: + name of temp file with dataset bytes, exact number of characters dumped. + """ + char_count = 0 + ds_iter = dataset.as_numpy_iterator() + with tempfile.NamedTemporaryFile( + delete=False, prefix='/tmp/ds_chars') as outfp: + while char_count < maxchars: + example = next(ds_iter) + for k in data_keys: + line = example[k] + b'\n' + char_count += len(line) + outfp.write(line) + return outfp.name, char_count + +def _train_sentencepiece(dataset: tf.data.Dataset, + *, + vocab_size: int, + maxchars: int = int(1e7), + assets_path: str, + model_path: str, + model_type: str = 'unigram', + character_coverage: float = 1.0, + data_keys=('text',)): + """Train SentencePiece tokenizer from subset of tf dataset. + Args: + dataset: tf.dataset + vocab_size: int: size of vocab tokens to train. + maxchars: int: number of characters to use for sentencepiece training. + model_path: str: path of model file to save vocab model to. + model_type: str: type of sentencepiece vocab to train. + character_coverage: amount of characters covered by the model, good defaults + are 0.9995 for languages with rich character set like Japanese or Chinese + and 1.0 for other languages with small character set. + data_keys: Tuple[str]: keys of dataset to use for training. + Returns: + path to the trained sentencepiece vocabulary model. + """ + if model_path.startswith('gs://'): + abs_model_path = model_path + else: + abs_model_path = os.path.abspath(os.path.expanduser(model_path)) + abs_assets_path = os.path.abspath(os.path.expanduser(assets_path)) + fname, _ = _dump_chars_to_textfile( + dataset, maxchars=maxchars, data_keys=data_keys) + with tempfile.NamedTemporaryFile( + delete=False, prefix='/tmp/sp_tmp') as model_fp: + pass # we just want a prefix'd tmp-filename + argstr = ' '.join([ + f'--input={fname}', f'--vocab_size={vocab_size}', + f'--character_coverage={character_coverage}', + f'--model_prefix={model_fp.name}', f'--model_type={model_type}' + ]) + SentencePieceTrainer.Train(argstr) + if jax.process_index() == 0: + # Use an intermediate filename that is renamed to the target name to address + # create and fill delays. + copy_rename_path = abs_model_path + '.rntmp' + if not model_path.startswith('gs://'): + tf.io.gfile.makedirs(abs_assets_path) + tf.io.gfile.copy(model_fp.name + '.model', copy_rename_path, overwrite=True) + tf.io.gfile.rename(copy_rename_path, abs_model_path, overwrite=True) + logging.info('copied %s to %s', model_fp.name + '.model', abs_model_path) + else: + while not tf.io.gfile.exists(abs_model_path): + time.sleep(1) + time.sleep(1) + return abs_model_path + +def train_tokenizer(dataset: tf.data.Dataset, + *, + assets_path: str, + vocab_path: str, + vocab_size: int, + max_corpus_chars: int, + data_keys: Tuple[str] = ('text',)): + """tokenizer training function""" + logging.info('SentencePiece vocab not found, building one from data.') + vocab_path = _train_sentencepiece( + dataset, + vocab_size=vocab_size, + maxchars=max_corpus_chars, + assets_path=assets_path, + model_path=vocab_path, + data_keys=data_keys) + logging.info('Model saved at %s', vocab_path) + + +def main(argv): + del argv + os.environ['TFDS_DATA_DIR'] = _DATASET_PATH.value + + read_config = tfds.ReadConfig( + shuffle_seed = 0, + ) + train_ds_builder = tfds.builder(_DATASET_NAME.value) + train_ds = train_ds_builder.as_dataset(split='train', read_config=read_config, shuffle_files=True) + train_tokenizer( + train_ds, + assets_path=_ASSETS_PATH.value, + vocab_path=os.path.join(_ASSETS_PATH.value, _VOCAB_MODEL_NAME.value), + vocab_size=_VOCAB_SIZE.value, + max_corpus_chars=_MAX_CORPUS_CHARS.value, + ) + + +if __name__ == '__main__': + app.run(main) diff --git a/maxtext-setup/maxtext/PREFLIGHT.md b/maxtext-setup/maxtext/PREFLIGHT.md new file mode 100644 index 0000000000000000000000000000000000000000..c04b546a6ef4e172bf7e181501b2cdeeaf78f02d --- /dev/null +++ b/maxtext-setup/maxtext/PREFLIGHT.md @@ -0,0 +1,37 @@ +# Optimization 1: Multihost recommended network settings +We included all the recommended network settings in [rto_setup.sh](https://github.com/google/maxtext/blob/main/rto_setup.sh). + +[preflight.sh](https://github.com/google/maxtext/blob/main/preflight.sh) will help you apply them based on GCE or GKE platform. + +Before you run ML workload on Multihost with GCE or GKE, simply apply `bash preflight.sh PLATFORM=[GCE or GKE]` to leverage the best DCN network performance. + +Here is an example for GCE: +``` +bash preflight.sh PLATFORM=GCE && python3 MaxText/train.py MaxText/configs/base.yml run_name=$YOUR_JOB_NAME +``` + +Here is an example for GKE: +``` +bash preflight.sh PLATFORM=GKE && python3 MaxText/train.py MaxText/configs/base.yml run_name=$YOUR_JOB_NAME +``` + +# Optimization 2: Numa binding (You can only apply this to v4 and v5p) +NUMA binding is recommended for enhanced performance, as it reduces memory latency and maximizes data throughput, ensuring that your high-performance applications operate more efficiently and effectively. + +For GCE, +[preflight.sh](https://github.com/google/maxtext/blob/main/preflight.sh) will help you install `numactl` dependency, so you can use it directly, here is an example: + +``` +bash preflight.sh PLATFORM=GCE && numactl --membind 0 --cpunodebind=0 python3 MaxText/train.py MaxText/configs/base.yml run_name=$YOUR_JOB_NAME +``` + +For GKE, +`numactl` should be built into your docker image from [maxtext_dependencies.Dockerfile](https://github.com/google/maxtext/blob/main/maxtext_dependencies.Dockerfile), so you can use it directly if you built the maxtext docker image. Here is an example + +``` +bash preflight.sh PLATFORM=GKE && numactl --membind 0 --cpunodebind=0 python3 MaxText/train.py MaxText/configs/base.yml run_name=$YOUR_JOB_NAME +``` + +1. `numactl`: This is the command-line tool used for controlling NUMA policy for processes or shared memory. It's particularly useful on multi-socket systems where memory locality can impact performance. +2. `--membind 0`: This option binds the memory allocation of the process to node 0. It means the process will allocate memory only from the memory of node 0. If node 0's memory is exhausted and more is required, the process will fail rather than using memory from other nodes. +3. `--cpunodebind=0`: This option binds the process to the CPUs of node 0. The process will only run on the CPUs of node 0, not on CPUs of other nodes. This can improve performance by ensuring that the process runs on CPUs that are close to the memory it is using. diff --git a/maxtext-setup/maxtext/README.md b/maxtext-setup/maxtext/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0be06cef6c7df12a13d0427fbbbbe19a0fa63aee --- /dev/null +++ b/maxtext-setup/maxtext/README.md @@ -0,0 +1,221 @@ + + + +[![Unit Tests](https://github.com/google/maxtext/actions/workflows/UnitTests.yml/badge.svg)](https://github.com/google/maxtext/actions/workflows/UnitTests.yml) + +# Overview + +MaxText is a **high performance**, **arbitrarily scalable**, **open-source**, **simple**, **easily forkable**, **well-tested**, **batteries included** LLM written in pure Python/Jax and targeting Google Cloud TPUs. MaxText typically achieves 55% to 60% model-flop utilization and scales from single host to very large clusters while staying simple and "optimization-free" thanks to the power of Jax and the XLA compiler. + +MaxText aims to be a launching off point for ambitious LLM projects both in research and production. We encourage users to start by experimenting with MaxText out of the box and then fork and modify MaxText to meet their needs. + +# Table of Contents + +* [Getting Started](#getting-started) +* [Runtime Performance Results](#runtime-performance-results) +* [Comparison To Alternatives](#comparison-to-alternatives) +* [Development](#development) +* [Features and Diagnostics](#features-and-diagnostics) + +# Getting Started + +We recommend starting with a single host first and then moving to multihost. + +## Getting Started: Download Dataset and Configure +You need to run these steps once per project prior to any local development or cluster experiments. + +1. Create two gcs buckets in your project, one for to downloading and retrieving the dataset and the other for storing the logs. +2. Download the dataset in your gcs bucket +``` +bash download_dataset.sh {GCS_PROJECT} {GCS_BUCKET_NAME} +``` +3. Set config values for `base_output_directory` and `dataset_path` in `configs/base.yml`. `tokenizer_path` is full path for loading the tokenizer. MaxText assumes these GCS buckets are created in the same project and that it has permissions to read and write from them. We also recommend reviewing the configurable options in `configs/base.yml`, for instance you may change the `steps` or `log_period` by either modifying `configs/base.yml` or by passing in `steps` and `log_period` as additional args to the `train.py` call. + +To run maxtext the TPUVMs must have permission to read the gcs bucket. These permissions are granted by service account roles, such as the `STORAGE ADMIN` role. + +## Getting Started: Local Development for single host + +Local development is a convenient way to run MaxText on a single host. It doesn't scale to +multiple hosts. + +1. [Create and SSH to the single-host TPU of your choice.](https://cloud.google.com/tpu/docs/users-guide-tpu-vm#creating_a_cloud_tpu_vm_with_gcloud) We recommend a `v4-8`. +2. Clone MaxText onto that TPUVM. +3. Within the root directory of that `git` repo, install dependencies by running: +``` +bash setup.sh +``` +4. After installation completes, run training with the command: +``` +python3 MaxText/train.py MaxText/configs/base.yml run_name=$YOUR_JOB_NAME +``` + +5. If you want to decode, you can decode as follows. +``` +python3 MaxText/decode.py MaxText/configs/base.yml run_name=$YOUR_JOB_NAME +``` +Be aware, these decodings will be random. To get high quality decodings you need pass in a checkpoint, typically via the `load_parameters_path` argument. + + +#### Running on NVIDIA GPUs +1. Use `bash docker_build_dependency_image.sh DEVICE=gpu` can be used to build a container with the required dependencies. +2. After installation is completed, run training with the command: +``` +python3 MaxText/train.py MaxText/configs/base.yml run_name=$YOUR_JOB_NAME +``` +3. If you want to decode, you can decode as follows. +``` +python3 MaxText/decode.py MaxText/configs/base.yml run_name=$YOUR_JOB_NAME +``` + +* If you see the following error when running inside a container, set a larger `--shm-size` (e.g. `--shm-size=1g`) +``` +Failed to execute XLA Runtime executable: run time error: custom call 'xla.gpu.all_reduce' failed: external/xla/xla/service/gpu/nccl_utils.cc:297: NCCL operation ncclCommInitRank(&comm, nranks, id, rank) failed: unhandled cuda error (run with NCCL_DEBUG=INFO for details); current tracing scope: all-reduce-start.2; current profiling annotation: XlaModule:#hlo_module=jit__unnamed_wrapped_function_,program_id=7#. +``` + +## Getting Starting: Multihost development +There are three patterns for running MaxText with more than one host. + +1. [GKE, recommended] [Running Maxtext with xpk](getting_started/Run_MaxText_via_xpk.md) - Quick Experimentation and Production support +2. [GCE] [Running Maxtext with Multihost Jobs](getting_started/Run_MaxText_via_multihost_job.md) - Long Running Production Jobs with Queued Resources +3. [GCE] [Running Maxtext with Multihost Runner](getting_started/Run_MaxText_via_multihost_runner.md) - Fast experiments via multiple ssh connections. + +## Getting Starting: Preflight Optimizations + +Once you've gotten workloads running, there are important optimizations you might want to put on your cluster. Please check the doc [PREFLIGHT.md](https://github.com/google/maxtext/blob/main/PREFLIGHT.md) + +# Runtime Performance Results + +## TPU v4 + +For a 22B model. See full run configs in `MaxText/configs/v4/` as `22b.sh`. + +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | ---------------- | ----- | +| 1x v4-128 | 156 | 56.7% | +| 2x v4-128 | 152 | 55.2% | +| 4x v4-128 | 149 | 54.3% | +| 8x v4-128 | 146 | 53.2% | + +For a 52B model. See full run configs in `MaxText/configs/v4/` as `52b.sh`. + +| Hardware | TFLOP/sec/chip | MFU | +| ----------- | ---------------- | ----- | +| 1x v4-384 | 154 | 56.0% | +| 2x v4-384 | 162 | 58.9% | # this is quirkily higher than single slice because of choices made by the compiler, not for a fundamental reason. + +## TPU v5e + +For 16B, 32B, 64B, and 128B models. See full run configs in `MaxText/configs/v5e/` as `16b.sh`, `32b.sh`, `64b.sh`, `128b.sh`. + +| Hardware | 16B TFLOP/sec/chip | 16B MFU | 32B TFLOP/sec/chip | 32B MFU | 64B TFLOP/sec/chip | 64B MFU | 128B TFLOP/sec/chip | 128B MFU | +| ----------- | -----------------: | ------- | -----------------: | ------- | -----------------: | ------- | ------------------: | -------- | +| 1x v5e-256 | 120 | 61.10% | 132 | 66.86% | 118 | 59.90% | 110 | 56.06% | +| 2x v5e-256 | 117 | 59.37% | 128 | 64.81% | 112 | 56.66% | 110 | 55.82% | +| 4x v5e-256 | 117 | 59.14% | 126 | 64.10% | 110 | 55.85% | 108 | 54.93% | +| 8x v5e-256 | 115 | 58.27% | 125 | 63.67% | 108 | 54.96% | 104 | 52.93% | +| 16x v5e-256 | 111 | 56.56% | 123 | 62.26% | 105 | 53.29% | 100 | 50.86% | +| 32x v5e-256 | 108 | 54.65% | 119 | 60.40% | 99 | 50.18% | 91 | 46.25% | + +More details on reproducing these results can be found in `MaxText/configs/README.md`. + + +# Comparison to Alternatives + +MaxText is heavily inspired by [MinGPT](https://github.com/karpathy/minGPT)/[NanoGPT](https://github.com/karpathy/nanoGPT), elegant standalone GPT implementations written in PyTorch and targeting Nvidia GPUs. MaxText is more complex but has an MFU more than three times the [17%](https://twitter.com/karpathy/status/1613250489097027584?cxt=HHwWgIDUhbixteMsAAAA) reported most recently with that codebase, is massively scalable and implements a key-value cache for efficient auto-regressive decoding. + +MaxText is more similar to [Nvidia/Megatron-LM](https://github.com/NVIDIA/Megatron-LM), a very well tuned LLM implementation targeting Nvidia GPUs. The two implementations achieve comparable MFUs. The difference in the codebases highlights the different programming strategies. MaxText is pure Python, relying heavily on the XLA compiler to achieve high performance. By contrast, Megatron-LM is a mix of Python and CUDA, relying on well-optimized CUDA kernels to achieve high performance. + +MaxText is also comparable to [Pax](https://github.com/google/paxml). Like Pax, MaxText provides high-performance and scalable implementations of LLMs in Jax. Pax focuses on enabling powerful configuration parameters, enabling developers to change the model by editing config parameters. By contrast, MaxText is a simple, concrete implementation of an LLM that encourages users to extend by forking and directly editing the source code. The right choice depends on your project's priorities. + +# Development + +Whether you are forking MaxText for your own needs or intending to contribute back to the community, we wanted to offer simple testing recipes. + +To run unit tests and lint, simply run: +``` +bash unit_test_and_lint.sh +``` + +The full suite of end-to-end tests is in `end_to_end/`. We run them with a nightly cadence. + +# Features and Diagnostics +## Collect Stack Traces +When running a Single Program, Multiple Data (SPMD) job on TPU VMs, the overall process can hang if there is any error or any VM hangs/crashes for some reason. In this scenario, capturing stack traces will help to identify and troubleshoot the issues for the jobs running on TPU VMs. + +The following configurations will help to debug a fault or when a program is stuck or hung somewhere by collecting stack traces. Change the parameter values accordingly in `MaxText/configs/base.yml`: +1. Set `collect_stack_trace: True` to enable collection of stack traces on faults or when the program is hung. This setting will periodically dump the traces for the program to help in debugging. To disable this, set `collect_stack_trace: False`. +2. Set `stack_trace_to_cloud: False` to display stack traces on console. `stack_trace_to_cloud: True` will create a temporary file in `/tmp/debugging` in the TPUs to store the stack traces. There is an agent running on TPU VMs that will periodically upload the traces from the temporary directory to cloud logging in the gcp project. You can view the traces in Logs Explorer on Cloud Logging using the following query: +``` +logName="projects//logs/tpu.googleapis.com%2Fruntime_monitor" +jsonPayload.verb="stacktraceanalyzer" +``` +3. `stack_trace_interval_seconds` signifies the duration in seconds between each stack trace collection event. Setting `stack_trace_interval_seconds: 600` will collect the stack traces every 600 seconds (10 minutes). + +Here is the related PyPI package: https://pypi.org/project/cloud-tpu-diagnostics. + +## Ahead of Time Compilation (AOT) +To compile your training run ahead of time, we provide a tool `train_compile.py`. This tool allows you to compile the main `train_step` in `train.py` for target hardware (e.g. a large number of v5e devices) without using the target hardware, and instead you may use only a CPU or a single VM from a different family. This compilation helps with two main goals: + +* It will flag any out of memory (OOM) information, such as when the `per_device_batch_size` is set too high, with an identical OOM stack trace as if it was compiled on the target hardware. + +* The ahead of time compilation can be saved and then loaded for fast startup and restart times on the target hardware. + +The tool `train_compile.py` is tightly linked to `train.py` and uses the same configuration file `configs/base.yml`. Although you don't need to run on a TPU, you do need to install `jax[tpu]` in addition to other dependencies, so we recommend running `setup.sh` to install these if you have not already done so. + +### Example AOT 1: Compile ahead of time basics +After installing the dependencies listed above, you are ready to compile ahead of time: +``` +# Run the below on a single machine, e.g. a CPU +python3 MaxText/train_compile.py MaxText/configs/base.yml compile_topology=v5e-256 compile_topology_num_slices=2 \ +global_parameter_scale=16 per_device_batch_size=4 +``` + +This will compile a 16B parameter MaxText model on 2 v5e pods. + +### Example AOT 2: Save compiled function, then load and run it +Here is an example that saves then loads the compiled `train_step`, starting with the save: + +**Step 1: Run AOT and save compiled function** +``` +# Run the below on a single machine, e.g. a CPU +export LIBTPU_INIT_ARGS="--xla_enable_async_all_gather=true" +python3 MaxText/train_compile.py MaxText/configs/base.yml compile_topology=v5e-256 \ +compile_topology_num_slices=2 \ +compiled_trainstep_file=my_compiled_train.pickle global_parameter_scale=16 \ +per_device_batch_size=4 steps=10000 learning_rate=1e-3 +``` + +**Step 2: Run train.py and load the compiled function** + +To load the compiled train_step, you just need to pass `compiled_trainstep_file=my_compiled_train.pickle` into `train.py`: +``` +# Run the below on each host of the target hardware, e.g. each host on 2 slices of v5e-256 +export LIBTPU_INIT_ARGS="--xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=example_load_compile \ +compiled_trainstep_file=my_compiled_train.pickle \ +global_parameter_scale=16 per_device_batch_size=4 steps=10000 learning_rate=1e-3 \ +base_output_directory=gs://my-output-bucket dataset_path=gs://my-dataset-bucket +``` + +In the save step of example 2 above we included exporting the compiler flag `LIBTPU_INIT_ARGS` and `learning_rate` because those affect the compiled object `my_compiled_train.pickle.` The sizes of the model (e.g. `global_parameter_scale`, `max_sequence_length` and `per_device_batch`) are fixed when you initially compile via `compile_train.py`, you will see a size error if you try to run the saved compiled object with different sizes than you compiled with. However a subtle note is that the **learning rate schedule** is also fixed when you run `compile_train` - which is determined by both `steps` and `learning_rate`. The optimizer parameters such as `adam_b1` are passed only as shaped objects to the compiler - thus their real values are determined when you run `train.py`, not during the compilation. If you do pass in different shapes (e.g. `per_device_batch`), you will get a clear error message reporting that the compiled signature has different expected shapes than what was input. If you attempt to run on different hardware than the compilation targets requested via `compile_topology`, you will get an error saying there is a failure to map the devices from the compiled to your real devices. Using different XLA flags or a LIBTPU than what was compiled will probably run silently with the environment you compiled in without error. However there is no guaranteed behavior in this case; you should run in the same environment you compiled in. + +## Supported Open Models + +MaxText supports training and inference of various open models. Follow user guides under [getting started](https://github.com/google/maxtext/tree/main/getting_started) section to know more. + +* [Gemma](https://ai.google.dev/gemma): a family of open-weights Large Language Model (LLM) by [Google DeepMind](https://deepmind.google/), based on Gemini research and technology. \ +You can run decode and finetuning using instructions mentioned [here](https://github.com/google/maxtext/blob/main/getting_started/Run_Gemma.md). diff --git a/maxtext-setup/maxtext/assets/tokenizer b/maxtext-setup/maxtext/assets/tokenizer new file mode 100644 index 0000000000000000000000000000000000000000..c966a9596eee01ef36f2be12a38f1be6c8570714 Binary files /dev/null and b/maxtext-setup/maxtext/assets/tokenizer differ diff --git a/maxtext-setup/maxtext/assets/tokenizer.gemma b/maxtext-setup/maxtext/assets/tokenizer.gemma new file mode 100644 index 0000000000000000000000000000000000000000..796efe9ab515c15e146ce7588e6d7b9b8134dbf8 --- /dev/null +++ b/maxtext-setup/maxtext/assets/tokenizer.gemma @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2 +size 4241003 diff --git a/maxtext-setup/maxtext/assets/tokenizer.llama2 b/maxtext-setup/maxtext/assets/tokenizer.llama2 new file mode 100644 index 0000000000000000000000000000000000000000..22bccbcb41ec929cf0c9dbe8f41036db82e5e773 Binary files /dev/null and b/maxtext-setup/maxtext/assets/tokenizer.llama2 differ diff --git a/maxtext-setup/maxtext/docker_build_dependency_image.sh b/maxtext-setup/maxtext/docker_build_dependency_image.sh new file mode 100644 index 0000000000000000000000000000000000000000..a1b0cfeaf67c9ebfd32650d411e6ff8ba64cca97 --- /dev/null +++ b/maxtext-setup/maxtext/docker_build_dependency_image.sh @@ -0,0 +1,77 @@ +#!/bin/bash + +# Copyright 2023 Google LLC +# +# 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. + +# Example command: +# bash docker_build_dependency_image.sh MODE=stable +# bash docker_build_dependency_image.sh MODE=nightly +# bash docker_build_dependency_image.sh MODE=stable JAX_VERSION=0.4.13 + +# Enable "exit immediately if any command fails" option +set -e + +export LOCAL_IMAGE_NAME=maxtext_base_image + +echo "Starting to build your docker image. This will take a few minutes but the image can be reused as you iterate." + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" + echo "$KEY"="$VALUE" +done + + +if [[ -z ${JAX_VERSION+x} ]] ; then + export JAX_VERSION=NONE + echo "Default JAX_VERSION=${JAX_VERSION}" +fi + +if [[ -z ${MODE} ]]; then + export MODE=stable + echo "Default MODE=${MODE}" + +fi + +if [[ -z ${DEVICE} ]]; then + export DEVICE=tpu + echo "Default DEVICE=${DEVICE}" +fi + +if [[ -z ${LIBTPU_GCS_PATH+x} ]] ; then + export LIBTPU_GCS_PATH=NONE + echo "Default LIBTPU_GCS_PATH=${LIBTPU_GCS_PATH}" + if [[ ${DEVICE} == "gpu" ]]; then + docker build --network host --build-arg MODE=${MODE} --build-arg JAX_VERSION=$JAX_VERSION --build-arg DEVICE=$DEVICE -f ./maxtext_gpu_dependencies.Dockerfile -t ${LOCAL_IMAGE_NAME} . + else + docker build --network host --build-arg MODE=${MODE} --build-arg JAX_VERSION=$JAX_VERSION --build-arg LIBTPU_GCS_PATH=$LIBTPU_GCS_PATH --build-arg DEVICE=$DEVICE -f ./maxtext_dependencies.Dockerfile -t ${LOCAL_IMAGE_NAME} . + fi +else + docker build --network host --build-arg MODE=${MODE} --build-arg JAX_VERSION=$JAX_VERSION --build-arg LIBTPU_GCS_PATH=$LIBTPU_GCS_PATH -f ./maxtext_dependencies.Dockerfile -t ${LOCAL_IMAGE_NAME} . + docker build --network host --build-arg CUSTOM_LIBTPU=true -f ./maxtext_libtpu_path.Dockerfile -t ${LOCAL_IMAGE_NAME} . +fi + +echo "" +echo "*************************" +echo "" + +echo "Built your base docker image and named it ${LOCAL_IMAGE_NAME}. +It only has the dependencies installed. Assuming you're on a TPUVM, to run the +docker image locally and mirror your local working directory run:" +echo "docker run -v $(pwd):/app --rm -it --privileged --entrypoint bash ${LOCAL_IMAGE_NAME}" +echo "" +echo "You can run MaxText and your development tests inside of the docker image. Changes to your workspace will automatically +be reflected inside the docker container." +echo "Once you want you upload your docker container to GCR, take a look at docker_upload_runner.sh" diff --git a/maxtext-setup/maxtext/docker_upload_runner.sh b/maxtext-setup/maxtext/docker_upload_runner.sh new file mode 100644 index 0000000000000000000000000000000000000000..c59c025667ad1b678c40c7c7be99a50b416fa96f --- /dev/null +++ b/maxtext-setup/maxtext/docker_upload_runner.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +# Copyright 2023 Google LLC +# +# 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. + +# This scripts takes a docker image that already contains the MaxText dependencies, copies the local source code in and +# uploads that image into GCR. Once in GCR the docker image can be used for development. + +# Each time you update the base image via a "bash docker_build_dependency_image.sh", there will be a slow upload process +# (minutes). However, if you are simply changing local code and not updating dependencies, uploading just takes a few seconds. + +# Example command: +# bash docker_upload_runner.sh CLOUD_IMAGE_NAME=${USER}_runner + +set -e + +export LOCAL_IMAGE_NAME=maxtext_base_image +export PROJECT=$(gcloud config get-value project) + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" + echo "$KEY"="$VALUE" +done + +export LOCAL_IMAGE_NAME_RUNNER=${LOCAL_IMAGE_NAME}__runner + +echo "In PROJECT=$PROJECT, uploading local image ${LOCAL_IMAGE_NAME} to CLOUD_IMAGE_NAME as ${CLOUD_IMAGE_NAME}" + +if [[ ! -v CLOUD_IMAGE_NAME ]]; then + echo "Erroring out because CLOUD_IMAGE_NAME is unset, please set it!" + exit 1 +fi + +docker build --build-arg BASEIMAGE=${LOCAL_IMAGE_NAME} -f ./maxtext_runner.Dockerfile -t ${LOCAL_IMAGE_NAME_RUNNER} . + +docker tag ${LOCAL_IMAGE_NAME_RUNNER} gcr.io/$PROJECT/${CLOUD_IMAGE_NAME}:latest +docker push gcr.io/$PROJECT/${CLOUD_IMAGE_NAME}:latest + +echo "All done, check out your artifacts at: gcr.io/$PROJECT/${CLOUD_IMAGE_NAME}" \ No newline at end of file diff --git a/maxtext-setup/maxtext/download_dataset.sh b/maxtext-setup/maxtext/download_dataset.sh new file mode 100644 index 0000000000000000000000000000000000000000..182683489b02da494005eb938a8a737ffe53477a --- /dev/null +++ b/maxtext-setup/maxtext/download_dataset.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +# Copyright 2023 Google LLC +# +# 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. + +# This script downloads c4/en/3.0.1 to your gcs bucket directory +# Usage bash download_dataset.sh <> <> +# Usage example: bash download_dataset.sh cloud-tpu-multipod-dev gs://maxtext-dataset + +function remove_trailing_slash { + if [[ $1 =~ /$ ]]; then # Check if the path ends with a slash + echo "${1::-1}" # Remove the last character + else + echo "$1" # Output the path as-is + fi +} + +gsutil -u $1 -m cp 'gs://allennlp-tensorflow-datasets/c4/en/3.0.1/*' $(remove_trailing_slash $2)/c4/en/3.0.1 diff --git a/maxtext-setup/maxtext/end_to_end/eval_assert.py b/maxtext-setup/maxtext/end_to_end/eval_assert.py new file mode 100644 index 0000000000000000000000000000000000000000..c879ce99f8fc3fdc16e698698ae5258d0fb57563 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/eval_assert.py @@ -0,0 +1,139 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: skip-file +"""Reads and asserts over target values""" +from absl import app +from typing import Sequence +from math import isclose +from google.cloud import storage +import json + + +def compute_avg_metric(metrics_file, target, start_line=10): + """ Reads and computes average of target value + If start_line is negative then uses the last lines, e.g. start from end + 1 - |start_line|""" + + + avg = 0 + i = 0 + with open(metrics_file, 'r', encoding='utf8') as file: + lines = file.readlines() + if start_line < 0: + start_line = len(lines) + start_line + for line in lines: + # skip the first start_line lines for burn in + if i >= start_line: + vals = json.loads(line) + avg += vals[target] + i+=1 + avg /= (i-start_line) + + return avg + + +def assert_metric_average(metrics_file, threshold, target): + avg_value = compute_avg_metric(metrics_file, target) + # Checks for acceptable performance by asserting that the average metric (e.g. TFLOPs) + # is greater than the threshold. + print(f'avg value of target {target} is {avg_value}') + assert avg_value >= float(threshold) + print('assert metric average passed.') + +def test_final_loss(metrics_file, target_loss): + target_loss = float(target_loss) + with open(metrics_file, 'r', encoding='utf8') as metrics: + use_last_n_data = 10 + avg_final_loss = compute_avg_metric(metrics_file, 'learning/loss', start_line= -1 * use_last_n_data) + print(f"Mean of last {use_last_n_data} losses is {avg_final_loss}") + print(f"Target loss is {target_loss}") + assert avg_final_loss < target_loss + print('Final loss test passed.') + +def test_checkpointing(metrics_file, target, dataset_type): + """Asserts over loss values from loaded checkpoint""" + metrics_file_saved = 'saved_' + metrics_file + metrics_file_restored = 'restored_' + metrics_file + + with open(metrics_file_saved, 'r', encoding='utf8') as saved,\ + open(metrics_file_restored, 'r', encoding='utf8') as restored: + saved_loss = json.loads(saved.readlines()[-1])[target] + restored_loss = json.loads(restored.readlines()[0])[target] + # Checks that checkpoint restore was successful by comparing loss of last + # step in saved checkpoint to loss of first step in restored checkpoint + print("saved loss: ", saved_loss) + print("restored loss: ", restored_loss) + if dataset_type=='c4': + assert isclose(saved_loss, restored_loss, rel_tol=0.1) + elif dataset_type=='c4-array_record': + assert saved_loss==restored_loss + else: + raise ValueError(f"Unknown dataset_type {dataset_type}. dataset_type must be c4, c4-array_record or synthetic") + print('checkpointing test passed.') + +def test_determinism(metrics_file, target): + """Asserts over loss values from two runs""" + run_1 = 'run_1_' + metrics_file + run_2 = 'run_2_' + metrics_file + + with open(run_1, 'r', encoding='utf8') as run_1_file,\ + open(run_2, 'r', encoding='utf8') as run_2_file: + run_1_loss = json.loads(run_1_file.readlines()[-1])[target] + run_2_loss = json.loads(run_2_file.readlines()[-1])[target] + # Check that the two runs have the same loss + print(f"Run 1 loss:{run_1_loss}", flush=True) + print(f"Run 2 loss:{run_2_loss}", flush=True) + assert run_1_loss==run_2_loss + print('determinism test passed.') + +def test_vocab_creation(target): + bucket_name = target.split("/")[2] + vocab_path = "/".join(target.split("/")[3:]) + storage_client = storage.Client() + assert storage.Blob(bucket=storage_client.bucket(bucket_name), name=vocab_path).exists(storage_client) + print('vocab creation test passed.') + +def test_start_step(metrics_file, start_step_target): + with open(metrics_file, 'r', encoding='utf8') as metrics: + start_step = json.loads(metrics.readlines()[0])["step"] + print(f"Start step is {start_step}, start step target is {start_step_target}") + assert start_step==float(start_step_target) + print("Start step test passed.") + +def main(argv: Sequence[str]) -> None: + + _, test_scenario, *test_vars = argv + + if test_scenario == 'metrics_average': + assert_metric_average(*test_vars) + elif test_scenario == 'checkpoint_save_restore': + test_checkpointing(*test_vars, dataset_type='c4') + elif test_scenario == 'grain_checkpoint_save_restore': + test_checkpointing(*test_vars, dataset_type='c4-array_record') + elif test_scenario == 'determinism': + test_determinism(*test_vars) + elif test_scenario == 'vocab_creation': + test_vocab_creation(*test_vars) + elif test_scenario == 'final_loss': + test_final_loss(*test_vars) + elif test_scenario == 'test_start_step': + test_start_step(*test_vars) + else: + raise ValueError(f"Unrecognized test_scenario {test_scenario}") + + +if __name__ == "__main__": + app.run(main) diff --git a/maxtext-setup/maxtext/end_to_end/llama_finetuning_test.sh b/maxtext-setup/maxtext/end_to_end/llama_finetuning_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..30c254fb15c37fda82b9188ad50f5a352b5c14cf --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/llama_finetuning_test.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +# This script is designed for internal use within Google. External users can adapt it by: +# - Updating GCS paths (gs://) to your accessible locations. +# - Using the checkpoint generated from train.py or available one in open source (https://llama.meta.com/llama-downloads/). + +set -e +idx=$(date +%Y-%m-%d-%H-%M)-$RANDOM + +base_ckpt_path=gs://maxtext-llama/test/2024-01-15-06-49/decode-ckpt-maxtext/0/items +BASE_OUTPUT_DIRECTORY=gs://runner-maxtext-logs +DATASET_PATH=gs://maxtext-dataset + +export LOSS_THRESHOLD=2.5 + +python3 MaxText/train.py MaxText/configs/base.yml run_name=runner_direct_${idx} base_output_directory=${BASE_OUTPUT_DIRECTORY} load_parameters_path=${base_ckpt_path} model_name='llama2-7b' dataset_path=${DATASET_PATH} async_checkpointing=false model_name='llama2-7b' ici_tensor_parallelism=4 steps=10 per_device_batch_size=.25 metrics_file='metrics.txt' + +# Assert training loss is smaller than input LOSS_THRESHOLD +python3 end_to_end/eval_assert.py final_loss metrics.txt $LOSS_THRESHOLD diff --git a/maxtext-setup/maxtext/end_to_end/test_checkpoint_compatibility.sh b/maxtext-setup/maxtext/end_to_end/test_checkpoint_compatibility.sh new file mode 100644 index 0000000000000000000000000000000000000000..c08815292315994a1723907c02cf29fe36dc445f --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_checkpoint_compatibility.sh @@ -0,0 +1,49 @@ +#!/bin/bash +set -ex + +if [ -f "run_*_metrics.txt" ]; then + rm run_*_metrics.txt + echo "removed existing run_*_metrics.txt" +fi + +RUN_NAME=${1}-$(date +%Y-%m-%d-%H-%M)-${RANDOM} +OUTPUT_PATH=${2} +DATASET_PATH=${3} +model_params=" base_emb_dim=384 base_num_query_heads=8 base_num_kv_heads=8 base_mlp_dim=192 base_num_decoder_layers=8 head_dim=128" + +echo "Mounting $DATASET_PATH to /tmp/gcsfuse/" +bash setup_gcsfuse.sh DATASET_GCS_BUCKET=$DATASET_PATH MOUNT_PATH=/tmp/gcsfuse/ + +echo "Run_1: Starting the first run using the grain input pipeline" + +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME steps=3 ${model_params}\ + max_target_length=128 per_device_batch_size=1\ + metrics_file=run_1_metrics.txt checkpoint_period=2 async_checkpointing=false\ + dataset_path=/tmp/gcsfuse base_output_directory=$OUTPUT_PATH\ + dataset_type=c4-array_record grain_worker_count=0\ + dataset_name=array-record/c4/en/3.0.1 eval_dataset_name=array-record/c4/en/3.0.1 + +echo +echo "Finished Run_1 at step 2" +echo "Run_2: Resuming using the tfds input pipeline" +echo + +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME steps=5 ${model_params}\ + max_target_length=128 per_device_batch_size=1\ + metrics_file=run_2_metrics.txt checkpoint_period=2 async_checkpointing=false\ + dataset_path=/tmp/gcsfuse base_output_directory=$OUTPUT_PATH\ + +echo +echo "Finished Run_2 at step 4" +echo "Run_3: Resuming using the grain input pipeline" +echo + +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME steps=7 ${model_params}\ + max_target_length=128 per_device_batch_size=1\ + metrics_file=run_3_metrics.txt checkpoint_period=2 async_checkpointing=false\ + dataset_path=/tmp/gcsfuse base_output_directory=$OUTPUT_PATH\ + dataset_type=c4-array_record grain_worker_count=0\ + dataset_name=array-record/c4/en/3.0.1 eval_dataset_name=array-record/c4/en/3.0.1 + +python3 end_to_end/eval_assert.py test_start_step run_2_metrics.txt 3.0 +python3 end_to_end/eval_assert.py test_start_step run_3_metrics.txt 5.0 diff --git a/maxtext-setup/maxtext/end_to_end/test_checkpoint_resharding.sh b/maxtext-setup/maxtext/end_to_end/test_checkpoint_resharding.sh new file mode 100644 index 0000000000000000000000000000000000000000..ae3b741a5fad0252dd7d97dbb4698d474d495649 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_checkpoint_resharding.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -ex + +RUN_NAME=${1}_$(date +%Y-%m-%d-%H) +OUTPUT_PATH=${2} +DATASET_PATH=${3} + +# Train and save checkpoint - sharded with DCN Data Parallelism + ICI FSDP Parallelism +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME steps=101\ + metrics_file='saved_metrics.txt' checkpoint_period=20 base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH\ + dcn_data_parallelism=2 dcn_fsdp_parallelism=1 ici_fsdp_parallelism=4 ici_tensor_parallelism=1 collect_stack_trace=False + +# Retrieve checkpoint - sharded with DCN Data Parallelism + ICI FSDP + Tensor Parallelism +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME steps=102\ + metrics_file='restored_metrics.txt' base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH\ + dcn_data_parallelism=2 dcn_fsdp_parallelism=1 ici_fsdp_parallelism=2 ici_tensor_parallelism=2 collect_stack_trace=False + +python3 end_to_end/eval_assert.py checkpoint_save_restore metrics.txt learning/loss diff --git a/maxtext-setup/maxtext/end_to_end/test_checkpointing.sh b/maxtext-setup/maxtext/end_to_end/test_checkpointing.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b1e676e10708a971000b4b9515d7fdff9b9669b --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_checkpointing.sh @@ -0,0 +1,63 @@ +#!/bin/bash +set -ex + +if [ -f "saved_metrics.txt" ]; then + rm saved_metrics.txt + echo "removed existing saved_metrics.txt" +fi + +if [ -f "restored_metrics.txt" ]; then + rm restored_metrics.txt + echo "removed existing restored_metrics.txt" +fi + +RUN_NAME=${1}-${4}-$(date +%Y-%m-%d-%H-%M)-${RANDOM} +OUTPUT_PATH=${2} +DATASET_PATH=${3} +COLLECT_STACK_TRACE=${4} +DATASET_TYPE=${5} +eval_metrics=checkpoint_save_restore +model_params=" base_emb_dim=384 base_num_query_heads=8 base_num_kv_heads=8 base_mlp_dim=192 base_num_decoder_layers=8 head_dim=128" +CMD_DATA="" + +if [ "$DATASET_TYPE" == "c4-array_record" ] +then + eval_metrics=grain_checkpoint_save_restore + echo "Using c4-array_record dataset type" + echo "Mounting $DATASET_PATH to /tmp/gcsfuse/" + bash setup_gcsfuse.sh DATASET_GCS_BUCKET=$DATASET_PATH MOUNT_PATH=/tmp/gcsfuse/ + DATASET_PATH=/tmp/gcsfuse/ + CMD_DATA=" grain_worker_count=0 dataset_type=c4-array_record dataset_name=array-record/c4/en/3.0.1 eval_dataset_name=array-record/c4/en/3.0.1" +fi + +#Train +CMD1="python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME steps=5 max_target_length=128 per_device_batch_size=1\ + metrics_file=saved_metrics.txt checkpoint_period=3 base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH\ + async_checkpointing=false collect_stack_trace=$COLLECT_STACK_TRACE" +CMD1+=$model_params +CMD1+=$CMD_DATA + +CMD2="python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME steps=5 max_target_length=128 per_device_batch_size=1\ + metrics_file=restored_metrics.txt base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH\ + async_checkpointing=false collect_stack_trace=$COLLECT_STACK_TRACE" +CMD2+=$model_params +CMD2+=$CMD_DATA + +echo +echo "Start the first training run" +echo "Command is:" +echo $CMD1 + +$CMD1 +# Wait for first train to finish +# process_id=$! +# wait $process_id +echo +echo "First training run done" +echo "Start the second training run" +echo "Command is:" +echo $CMD2 + +$CMD2 + +python3 end_to_end/eval_assert.py $eval_metrics metrics.txt learning/loss diff --git a/maxtext-setup/maxtext/end_to_end/test_convergence_1b_params.sh b/maxtext-setup/maxtext/end_to_end/test_convergence_1b_params.sh new file mode 100644 index 0000000000000000000000000000000000000000..38108b1c5f71834c8866173668ba62e5a600d142 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_convergence_1b_params.sh @@ -0,0 +1,52 @@ +#!/bin/bash +set -ex + +echo "Running test_convergence_1b_params.sh" +# Run this on 64 chips to achieve a loss value of ~2.5 after 20400 steps, or ~2.7 after 10200 steps (v4-128) +# +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# LOSS_THRESHOLD (Optional, default is 100.0 ) +# +# Example to invoke this script: +# bash end_to_end/test_convergence_1b_params.sh RUN_NAME="" OUTPUT_PATH="gs://" DATASET_PATH="gs://" LOSS_THRESHOLD=100.0 + +export LOSS_THRESHOLD=100.0 # Set to large value so test is guaranteed to pass. +export STEPS=20400 # Run for 20B tokens for a 1B sized mode for "chinchilla" scaling https://arxiv.org/abs/2203.15556 + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +if [ -n "$RUN_NAME" ]; +then + export M_RUN_NAME=$RUN_NAME +fi + +if [ "$DATASET_TYPE" == "c4-array_record" ] +then + EVAL_METRICS=grain_checkpoint_save_restore + echo "Using c4-array_record dataset type" + echo "Mounting $DATASET_PATH to /tmp/gcsfuse/" + bash setup_gcsfuse.sh DATASET_GCS_BUCKET=$DATASET_PATH MOUNT_PATH=/tmp/gcsfuse/ + DATASET_PATH=/tmp/gcsfuse/ + CMD_DATA=" dataset_type=c4-array_record dataset_name=array-record/c4/en/3.0.1 eval_dataset_name=array-record/c4/en/3.0.1" +fi + +TRAIN_CMD="python3 MaxText/train.py MaxText/configs/base.yml\ + steps=$STEPS per_device_batch_size=8.0 learning_rate=3e-4 enable_checkpointing=false \ + max_target_length=2048 global_parameter_scale=1 \ + enable_profiler=false metrics_file=metrics.txt base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH log_period=150 remat_policy=minimal enable_data_shuffling=false" +TRAIN_CMD+=$CMD_DATA + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +$TRAIN_CMD + +# Assert training loss is smaller than input LOSS_THRESHOLD +python3 end_to_end/eval_assert.py final_loss metrics.txt $LOSS_THRESHOLD diff --git a/maxtext-setup/maxtext/end_to_end/test_decode.sh b/maxtext-setup/maxtext/end_to_end/test_decode.sh new file mode 100644 index 0000000000000000000000000000000000000000..586f1f2c5d97dd072d0ed8b2454027d87bc5ee50 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_decode.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -ex + +NUM_TOKEN_THRESHOLD=${1} +OUTPUT_PATH=${2} +DATASET_PATH=${3} +# Run name is optional 4th input - our daily XLML tests will use one. + + +if [ -z ${4} ] +then + RUN_NAME=${USER}_$(date +%Y-%m-%d-%H-%M-%S)-${RANDOM} +else + RUN_NAME=${4}_$(date +%Y-%m-%d-%H)-${RANDOM} +fi + +if [ -z ${5} ] +then + ICI_TENSOR_PARALLELISM=4 +else + ICI_TENSOR_PARALLELISM=${5} +fi + +# Decode without checkpoint +python3 MaxText/decode.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=50 enable_checkpointing=False metrics_file=/tmp/${RUN_NAME}_metrics.txt \ + base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH \ + attention=dot_product ici_tensor_parallelism=${ICI_TENSOR_PARALLELISM} diff --git a/maxtext-setup/maxtext/end_to_end/test_determinism.sh b/maxtext-setup/maxtext/end_to_end/test_determinism.sh new file mode 100644 index 0000000000000000000000000000000000000000..9d9c066fcc4925ccdb37c1c5bd6dee41f3aea53f --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_determinism.sh @@ -0,0 +1,31 @@ +#!/bin/bash +set -ex + +RUN_NAME=${1}_$(date +%Y-%m-%d-%H) +OUTPUT_PATH=${2} +DATASET_PATH=${3} +DATASET_TYPE=${4} + +if [ "$DATASET_TYPE" == "c4-array_record" ] +then + EVAL_METRICS=grain_checkpoint_save_restore + echo "Using c4-array_record dataset type" + echo "Mounting $DATASET_PATH to /tmp/gcsfuse/" + bash setup_gcsfuse.sh DATASET_GCS_BUCKET=$DATASET_PATH MOUNT_PATH=/tmp/gcsfuse/ + DATASET_PATH=/tmp/gcsfuse/ + CMD_DATA=" dataset_type=c4-array_record dataset_name=array-record/c4/en/3.0.1 eval_dataset_name=array-record/c4/en/3.0.1" +fi + +#Train +CMD1="python3 MaxText/train.py MaxText/configs/base.yml run_name=${RUN_NAME}_1 steps=5 metrics_file=run_1_metrics.txt\ + enable_checkpointing=False enable_data_shuffling=True enable_dropout=False base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH" +CMD1+=$CMD_DATA + + +CMD2="python3 MaxText/train.py MaxText/configs/base.yml run_name=${RUN_NAME}_2 steps=5 metrics_file=run_2_metrics.txt\ + enable_checkpointing=False enable_data_shuffling=True enable_dropout=False base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH" +CMD2+=$CMD_DATA + +$CMD1 +$CMD2 +python3 end_to_end/eval_assert.py determinism metrics.txt learning/loss diff --git a/maxtext-setup/maxtext/end_to_end/test_gemma.sh b/maxtext-setup/maxtext/end_to_end/test_gemma.sh new file mode 100644 index 0000000000000000000000000000000000000000..76fc1f2363779b5af2edc065e296096069197358 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_gemma.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -ex +idx=$(date +%Y-%m-%d-%H-%M)-${RANDOM} +# convert 2.5B checkpoint +export base_model_path=gs://maxtext-gemma/flax/2b +export maxtext_model_path=gs://maxtext-gemma/2b/${idx} +python MaxText/convert_gemma_chkpt.py --base_model_path ${base_model_path} --maxtext_model_path ${maxtext_model_path} --model_size 2b +# Test Gemma 2.5B decode +python MaxText/decode.py MaxText/configs/base.yml tokenizer_path=assets/tokenizer.gemma load_parameters_path=${maxtext_model_path}/0/items per_device_batch_size=1 run_name=runner_${idx} max_prefill_predict_length=8 max_target_length=16 dataset_type=synthetic steps=10 async_checkpointing=false model_name=gemma-2b attention=dot_product prompt="I love to" autoregressive_decode_assert=" travel and I love to write. I" +python MaxText/decode.py MaxText/configs/base.yml tokenizer_path=assets/tokenizer.gemma load_parameters_path=${maxtext_model_path}/0/items per_device_batch_size=1 run_name=runner_${idx} max_prefill_predict_length=8 max_target_length=16 dataset_type=synthetic steps=10 async_checkpointing=false model_name=gemma-2b attention=dot_product prompt="I love to" autoregressive_decode_assert=" travel and I love to write. I" decode_sampling_strategy=weighted decode_sampling_temperature=.00001 +python MaxText/decode.py MaxText/configs/base.yml tokenizer_path=assets/tokenizer.gemma load_parameters_path=${maxtext_model_path}/0/items per_device_batch_size=1 run_name=runner_${idx} max_prefill_predict_length=8 max_target_length=16 dataset_type=synthetic steps=10 async_checkpointing=false model_name=gemma-2b attention=dot_product prompt="I love to" autoregressive_decode_assert=" travel and I love to write. I" decode_sampling_strategy=nucleus decode_sampling_nucleus_p=0 +python MaxText/decode.py MaxText/configs/base.yml tokenizer_path=assets/tokenizer.gemma load_parameters_path=${maxtext_model_path}/0/items per_device_batch_size=1 run_name=runner_${idx} max_prefill_predict_length=8 max_target_length=16 dataset_type=synthetic steps=10 async_checkpointing=false model_name=gemma-2b attention=dot_product prompt="I love to" autoregressive_decode_assert=" travel and I love to write. I" decode_sampling_strategy=topk decode_sampling_top_k=1 + +# convert 7B checkpoint +export base_model_path=gs://maxtext-gemma/flax/7b +export maxtext_model_path=gs://maxtext-gemma/7b/${idx} +python MaxText/convert_gemma_chkpt.py --base_model_path ${base_model_path} --maxtext_model_path ${maxtext_model_path} --model_size 7b +# Test Gemma 7B decode +python MaxText/decode.py MaxText/configs/base.yml tokenizer_path=assets/tokenizer.gemma load_parameters_path=${maxtext_model_path}/0/items per_device_batch_size=1 run_name=runner_${idx} max_prefill_predict_length=8 max_target_length=16 dataset_type=synthetic steps=10 async_checkpointing=false model_name=gemma-7b attention=dot_product prompt="I love to" autoregressive_decode_assert=" use this product in my hair. It" diff --git a/maxtext-setup/maxtext/end_to_end/test_generate_param_only_checkpoint.sh b/maxtext-setup/maxtext/end_to_end/test_generate_param_only_checkpoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..d768b37b54b8de52cfede5c30b6ab5512d6acc6b --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_generate_param_only_checkpoint.sh @@ -0,0 +1,117 @@ +#!/bin/bash + +set -uex + +helpFunction() +{ + echo "" + echo "Usage: $0 " + echo -e "\t-n dry_run is true " + echo -e "\t-r runid: run_test_model_0b" + echo -e "\t-d dataset_path: gs://test-maxtext-dataset" + echo -e "\t-o output_path: gs://test-maxtext-output" + echo -e "\t-i ici_tensor_parallelism: 8" + echo -e "\t-a attention: flash" + exit 1 # Exit script after printing help +} + +# Default option values +dry_run=false +run_id=test_model_0b_$(date +%Y-%m-%d-%H) +dataset_path=gs://test-maxtext-dataset +base_output_directory=gs://test-maxtext-output +ici_tensor_parallelism=8 +attention=flash + +while getopts "nr:d:o:t:i:a:" opt +do + case "$opt" in + n ) dry_run=true ;; + r ) run_id="$OPTARG" ;; + d ) dataset_path="$OPTARG";; + o ) base_output_directory="$OPTARG";; + i ) ici_tensor_parallelism="$OPTARG" ;; + a ) attention="$OPTARG" ;; + ? ) helpFunction ;; # Print helpFunction in case parameter is non-existent + esac +done + +echo +echo "Running: ./$0 dataset_path=${dataset_path} base_output_directory=${base_output_directory}" +echo " dry_run=${dry_run} run_id=${run_id} " +echo " ici_tensor_parallelism=${ici_tensor_parallelism} attention=${attention}" +echo + +if "$dry_run"; then + cmd=echo +else + cmd='' +fi + +training_ckpt_run_id=${run_id}-ckpt-train-steps-5 +decode_ckpt_run_id=${run_id}-decode-ckpt-train-steps-5 +model_params="base_emb_dim=384 base_num_query_heads=8 base_num_kv_heads=8 base_mlp_dim=192 base_num_decoder_layers=8 head_dim=128" + +echo +echo "Create a test training checkpoint" +echo +$cmd python3 MaxText/train.py MaxText/configs/base.yml \ +run_name=${training_ckpt_run_id} \ +base_output_directory=${base_output_directory} \ +dataset_path=${dataset_path} attention=${attention} \ +steps=5 checkpoint_period=3 async_checkpointing=false \ +${model_params} \ + + +if [ $? -eq 0 ] +then + echo + echo "Successfully created a training checkpoint" + echo "Checkpoint path: ${base_output_directory}/${training_ckpt_run_id}/checkpoints/3/items" +else + echo + echo "Could not create a training checkpoint" >&2 + exit 1 +fi + +echo +echo "Generate a decode checkpoint from the test training checkpoint" +echo + +$cmd python3 MaxText/generate_param_only_checkpoint.py MaxText/configs/base.yml \ +run_name=${decode_ckpt_run_id} attention=${attention} \ +base_output_directory=${base_output_directory} \ +dataset_path=${dataset_path} async_checkpointing=false \ +load_full_state_path=${base_output_directory}/${training_ckpt_run_id}/checkpoints/3/items \ +${model_params} \ + + +if [ $? -eq 0 ] +then + echo "Successfully created an decode checkpoint" + echo "Checkpoint path: ${base_output_directory}/${decode_ckpt_run_id}/checkpoints/0/items" + +else + echo "Could not create an decode checkpoint" >&2 + exit 1 +fi + +echo +echo "Run decode using the generated checkpoint" +echo +$cmd python3 MaxText/decode.py MaxText/configs/base.yml \ +run_name=${run_id}-decode-steps-50 \ +base_output_directory=${base_output_directory} \ +dataset_path=${dataset_path} \ +load_parameters_path=${base_output_directory}/${decode_ckpt_run_id}/checkpoints/0/items \ +attention=dot_product ici_tensor_parallelism=${ici_tensor_parallelism} steps=50 \ +metrics_file=/tmp/${run_id}_metrics.txt async_checkpointing=false max_target_length=128 per_device_batch_size=1 \ +${model_params} \ + +if [ $? -eq 0 ] +then + echo "Successfully ran decode using decode optimized checkpoint" +else + echo "Could not run decode decode optimized checkpoint" >&2 + exit 1 +fi diff --git a/maxtext-setup/maxtext/end_to_end/test_gpt3.sh b/maxtext-setup/maxtext/end_to_end/test_gpt3.sh new file mode 100644 index 0000000000000000000000000000000000000000..7dd0b315afb64bd9c640a5ca46950a9afc64ddb5 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_gpt3.sh @@ -0,0 +1,16 @@ +set -euox pipefail + +TIMESTAMP=$(date +%Y%m%d-%H%M) +export PAXML_CKPT_PATH=gs://maxtext-gpt3/ckpt_test/paxml/checkpoints/checkpoint_00000000/state +export OUTPUT_PATH=gs://maxtext-gpt3/tests +export RUN_NAME=test_${TIMESTAMP} + +# convert gpt3-52k model +python3 MaxText/convert_gpt3_ckpt_from_paxml.py --paxml-ckpt-path=${PAXML_CKPT_PATH} --maxtext-model-name=gpt3-52k --run-name=${RUN_NAME} --base-output-directory=${OUTPUT_PATH} + +# Run gpt3-52k with the converted ckpt +python3 MaxText/train.py MaxText/configs/base.yml run_name=${RUN_NAME} model_name=gpt3-52k\ + steps=10 per_device_batch_size=6 enable_checkpointing=true async_checkpointing=false\ + enable_profiler=false remat_policy=full\ + max_target_length=2048 base_output_directory=${OUTPUT_PATH}\ + dataset_type=synthetic diff --git a/maxtext-setup/maxtext/end_to_end/test_llama2.sh b/maxtext-setup/maxtext/end_to_end/test_llama2.sh new file mode 100644 index 0000000000000000000000000000000000000000..9594688ebd59caca54549b94bff1afb6bc1b9396 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_llama2.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +# This script is designed for internal use within Google. External users can adapt it by: +# - Updating GCS paths (gs://) to your accessible locations. +# - Using the checkpoint generated from train.py or available one in open source (https://llama.meta.com/llama-downloads/). + +set -ex +idx=$(date +%Y-%m-%d-%H-%M)-${RANDOM} + +export M_ENABLE_CHECKPOINTING=true +export M_BASE_OUTPUT_DIRECTORY=gs://runner-maxtext-logs +export M_DATASET_PATH=gs://maxtext-dataset +export M_ASYNC_CHECKPOINTING=false + +pip install torch --index-url https://download.pytorch.org/whl/cpu +gcloud storage cp -r gs://maxtext-llama/llama2-7b/meta-ckpt /tmp/ + +export converted_checkpoint_path=gs://maxtext-llama/test/${idx}/decode-ckpt-maxtext + +python3 MaxText/llama_or_mistral_ckpt.py --base-model-path /tmp/meta-ckpt --model-size llama2-7b --maxtext-model-path ${converted_checkpoint_path} + +export converted_checkpoint=${converted_checkpoint_path}/0/items + +# Load after directly from parameter checkpoint +python3 MaxText/decode.py MaxText/configs/base.yml load_parameters_path=${converted_checkpoint} run_name=runner_direct_${idx} per_device_batch_size=1 model_name='llama2-7b' ici_tensor_parallelism=4 max_prefill_predict_length=4 max_target_length=16 prompt="I love to" autoregressive_decode_assert="read. I love to write. I love to share." attention=dot_product + +#Finetuning +python3 MaxText/train.py MaxText/configs/base.yml load_parameters_path=${converted_checkpoint} run_name=runner_finetuning_${idx} per_device_batch_size=1 model_name='llama2-7b' ici_tensor_parallelism=4 steps=10 max_target_length=1024 per_device_batch_size=1 checkpoint_period=5 + +# Pre-training +python3 MaxText/train.py MaxText/configs/base.yml run_name=runner_pretraining_${idx} per_device_batch_size=1 model_name='llama2-7b' ici_tensor_parallelism=4 steps=10 max_target_length=1024 per_device_batch_size=1 + + +# Generate parameter checkpoint from Llama2's "fine-tuning" run +unset M_LOAD_PARAMETERS_PATH +export PARAMETER_CHECKPOINT_RUN=generate_param_only_checkpoint_${idx} +python3 MaxText/generate_param_only_checkpoint.py MaxText/configs/base.yml load_full_state_path=${M_BASE_OUTPUT_DIRECTORY}/runner_finetuning_${idx}/checkpoints/5/items run_name=${PARAMETER_CHECKPOINT_RUN} model_name='llama2-7b' force_unroll=true + +export new_ckpt_path=${M_BASE_OUTPUT_DIRECTORY}/${PARAMETER_CHECKPOINT_RUN}/checkpoints/0/items + +# Load fine-tuned parameter checkpoint into decode.py +python3 MaxText/decode.py MaxText/configs/base.yml load_parameters_path=${new_ckpt_path} run_name=runner_decode_finetuned_${idx} per_device_batch_size=1 model_name='llama2-7b' ici_tensor_parallelism=4 max_prefill_predict_length=4 max_target_length=16 prompt="I love to" attention=dot_product scan_layers=false diff --git a/maxtext-setup/maxtext/end_to_end/test_mistral.sh b/maxtext-setup/maxtext/end_to_end/test_mistral.sh new file mode 100644 index 0000000000000000000000000000000000000000..56eccadfe4e25e504702a047b5998d0170d87872 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_mistral.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +# This script is designed for internal use within Google. External users can adapt it by: +# - Updating GCS paths (gs://) to your accessible locations. +# - Using the checkpoint generated from train.py or available one in open source (i.e. https://files.mistral-7b-v0-1.mistral.ai/mistral-7B-v0.1.tar). + +set -ex +idx=$(date +%Y-%m-%d-%H-%M)-${RANDOM} + +export M_ENABLE_CHECKPOINTING=true +export M_BASE_OUTPUT_DIRECTORY=gs://runner-maxtext-logs +export M_DATASET_PATH=gs://maxtext-dataset +export M_ASYNC_CHECKPOINTING=false + +# Download checkpoint, convert it to MaxText, and run inference +pip3 install torch +gsutil -m cp -r gs://maxtext-external/mistral-7B-v0.1 /tmp +python3 MaxText/llama_or_mistral_ckpt.py --base-model-path /tmp/mistral-7B-v0.1 --model-size mistral-7b --maxtext-model-path gs://maxtext-mistral/test/${idx}/decode-ckpt-maxtext/ +python3 MaxText/decode.py MaxText/configs/base.yml load_parameters_path=gs://maxtext-mistral/test/${idx}/decode-ckpt-maxtext/0/items run_name=runner_direct_${idx} per_device_batch_size=1 model_name='mistral-7b' tokenizer_path=gs://maxtext-external/mistral-7B-v0.1/tokenizer.mistral ici_tensor_parallelism=4 max_prefill_predict_length=4 max_target_length=16 prompt="I love to" autoregressive_decode_assert="read. I love to read about the Bible. I love" attention=dot_product + +# Training +python3 MaxText/train.py MaxText/configs/base.yml load_parameters_path=gs://maxtext-mistral/test/${idx}/decode-ckpt-maxtext/0/items run_name=runner_${idx} per_device_batch_size=1 model_name='mistral-7b' ici_tensor_parallelism=4 steps=10 max_target_length=1024 tokenizer_path=gs://maxtext-external/mistral-7B-v0.1/tokenizer.mistral diff --git a/maxtext-setup/maxtext/end_to_end/test_mixtral.sh b/maxtext-setup/maxtext/end_to_end/test_mixtral.sh new file mode 100644 index 0000000000000000000000000000000000000000..bf5218a23e78f3c109fb83aa7c7a40bb5a57dd6c --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_mixtral.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +# This script is designed for internal use within Google. External users can adapt it by: +# - Updating GCS paths (gs://) to your accessible locations. +# - Using the checkpoint generated from train.py or available one in open source (i.e. https://files.mixtral-8x7b-v0-1.mistral.ai/Mixtral-8x7B-v0.1-Instruct.tar). + +set -ex +idx=$(date +%Y-%m-%d-%H-%M)-${RANDOM} + +export M_ENABLE_CHECKPOINTING=true +export M_BASE_OUTPUT_DIRECTORY=gs://runner-maxtext-logs +export M_DATASET_PATH=gs://maxtext-dataset +export M_ASYNC_CHECKPOINTING=false + +# Download checkpoint, convert it to MaxText, and run inference +pip3 install torch +gsutil -m cp -r gs://maxtext-external/mixtral-8x7B-v0.1-Instruct /tmp +python3 MaxText/llama_or_mistral_ckpt.py --base-model-path /tmp/mixtral-8x7B-v0.1-Instruct --model-size mixtral-8x7b --maxtext-model-path gs://maxtext-mixtral/test/${idx}/decode-ckpt-maxtext/ +python3 MaxText/decode.py MaxText/configs/base.yml load_parameters_path=gs://maxtext-mixtral/test/${idx}/decode-ckpt-maxtext/0/items run_name=runner_direct_${idx} per_device_batch_size=1 model_name=mixtral-8x7b tokenizer_path=gs://maxtext-external/mixtral-8x7B-v0.1-Instruct/tokenizer.mistral ici_tensor_parallelism=4 ici_fsdp_parallelism=16 max_prefill_predict_length=11 max_target_length=28 prompt="[INST] I love to [/INST]" autoregressive_decode_assert="That's great to hear! I love to learn new things and explore different interests" attention=dot_product + +# Training +python3 MaxText/train.py MaxText/configs/base.yml load_parameters_path=gs://maxtext-mixtral/test/${idx}/decode-ckpt-maxtext/0/items run_name=runner_${idx} per_device_batch_size=1 model_name=mixtral-8x7b ici_tensor_parallelism=4 ici_fsdp_parallelism=16 steps=10 max_target_length=1024 tokenizer_path=gs://maxtext-external/mixtral-8x7B-v0.1-Instruct/tokenizer.mistral diff --git a/maxtext-setup/maxtext/end_to_end/test_tflops.sh b/maxtext-setup/maxtext/end_to_end/test_tflops.sh new file mode 100644 index 0000000000000000000000000000000000000000..81caa6f861271762cf081e57f8ef266e132aa9f8 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_tflops.sh @@ -0,0 +1,22 @@ +#!/bin/bash +set -ex + +USER=${1} +TFLOP_THRESHOLD=${2} +OUTPUT_PATH=${3} +DATASET_PATH=${4} + + +if [ -z ${5} ] +then + RUN_NAME=${USER}_$(date +%Y-%m-%d-%H-%M-%S)-${RANDOM} +else + RUN_NAME=${5}_$(date +%Y-%m-%d-%H)-${RANDOM} +fi + +#Train +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=150 reuse_example_batch=1 remat_policy='full' enable_profiler=True enable_checkpointing=False metrics_file='metrics.txt'\ + base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH log_period=150 + +python3 end_to_end/eval_assert.py metrics_average metrics.txt $TFLOP_THRESHOLD perf/per_device_tflops_per_sec diff --git a/maxtext-setup/maxtext/end_to_end/test_tflops_16b_params.sh b/maxtext-setup/maxtext/end_to_end/test_tflops_16b_params.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e992305fad6987d2ee77c6c0d8bd7af111e6ddb --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_tflops_16b_params.sh @@ -0,0 +1,38 @@ +#!/bin/bash +echo "Running test_tflops_16b_params.sh" + +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# TFLOP_THRESHOLD (Optional, default is 0 ) +# +# Example to invoke this script: +# bash end_to_end/test_tflops_16b_params.sh RUN_NAME=""" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" TFLOP_THRESHOLD=0 + +# Stop execution if any command exits with error +set -ex + +export TFLOP_THRESHOLD=0 +export PLATFORM="gce" + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=150 per_device_batch_size=6 enable_checkpointing=false\ + enable_profiler=false remat_policy=full\ + max_target_length=2048 metrics_file='metrics.txt' base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH log_period=150 global_parameter_scale=16 + +# Assert TFLOP/s +python3 end_to_end/eval_assert.py metrics_average metrics.txt $TFLOP_THRESHOLD perf/per_device_tflops_per_sec diff --git a/maxtext-setup/maxtext/end_to_end/test_tflops_32b_params.sh b/maxtext-setup/maxtext/end_to_end/test_tflops_32b_params.sh new file mode 100644 index 0000000000000000000000000000000000000000..59f0585a3b5a4b2bee40401ae0f04c8d69e0788f --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_tflops_32b_params.sh @@ -0,0 +1,38 @@ +#!/bin/bash +echo "Running test_tflops_32b_params.sh" + +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# TFLOP_THRESHOLD (Optional, default is 0 ) +# +# Example to invoke this script: +# bash end_to_end/test_tflops_32b_params.sh RUN_NAME=""" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" TFLOP_THRESHOLD=0 + +# Stop execution if any command exits with error +set -ex + +export TFLOP_THRESHOLD=0 +export PLATFORM="gce" + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=150 per_device_batch_size=4 enable_checkpointing=false\ + enable_profiler=false remat_policy=full\ + max_target_length=2048 metrics_file='metrics.txt' base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH log_period=150 global_parameter_scale=32 + +# Assert TFLOP/s +python3 end_to_end/eval_assert.py metrics_average metrics.txt $TFLOP_THRESHOLD perf/per_device_tflops_per_sec diff --git a/maxtext-setup/maxtext/end_to_end/test_tflops_64b_params.sh b/maxtext-setup/maxtext/end_to_end/test_tflops_64b_params.sh new file mode 100644 index 0000000000000000000000000000000000000000..7c05d74134952dcc7e25672f5de3a179bfa9fd5e --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_tflops_64b_params.sh @@ -0,0 +1,38 @@ +#!/bin/bash +echo "Running test_tflops_64b_params.sh" + +# Command Flags: +# OUTPUT_PATH (Required, unless base_output_directory is already set in base.yml) +# DATASET_PATH (Required, unless dataset_path is already set in base.yml) +# RUN_NAME (Required, unless run_name is already set in base.yml or running with XPK/GKE) +# PLATFORM (Optional, can be "gke" or "gce", default is "gce") +# TFLOP_THRESHOLD (Optional, default is 0 ) +# +# Example to invoke this script: +# bash end_to_end/test_tflops_64b_params.sh RUN_NAME=""" OUTPUT_PATH="gs://" DATASET_PATH="gs://" PLATFORM="gke" TFLOP_THRESHOLD=0 + +# Stop execution if any command exits with error +set -ex + +export TFLOP_THRESHOLD=0 +export PLATFORM="gce" + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +# Set up network optimizations +bash preflight.sh PLATFORM=$PLATFORM + +# Train +export LIBTPU_INIT_ARGS="--xla_tpu_enable_data_parallel_all_reduce_opt=true --xla_tpu_data_parallel_opt_different_sized_ops=true --xla_tpu_enable_async_collective_fusion=true --xla_tpu_enable_async_collective_fusion_fuse_all_gather=true --xla_tpu_enable_async_collective_fusion_multiple_steps=true --xla_tpu_overlap_compute_collective_tc=true --xla_enable_async_all_gather=true" +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME\ + steps=150 per_device_batch_size=2 enable_checkpointing=false\ + enable_profiler=false remat_policy=full\ + max_target_length=2048 metrics_file='metrics.txt' base_output_directory=$OUTPUT_PATH\ + dataset_path=$DATASET_PATH log_period=150 global_parameter_scale=64 + +# Assert TFLOP/s +python3 end_to_end/eval_assert.py metrics_average metrics.txt $TFLOP_THRESHOLD perf/per_device_tflops_per_sec diff --git a/maxtext-setup/maxtext/end_to_end/test_vocab_creation.sh b/maxtext-setup/maxtext/end_to_end/test_vocab_creation.sh new file mode 100644 index 0000000000000000000000000000000000000000..dafd4f00ffb4fb4b629d0747788c7411225f16e6 --- /dev/null +++ b/maxtext-setup/maxtext/end_to_end/test_vocab_creation.sh @@ -0,0 +1,14 @@ +#!/bin/bash +set -ex + +RUN_NAME=${1}_$(date +%Y-%m-%d-%H) +OUTPUT_PATH=${2} +DATASET_PATH=${3} +VOCAB_PATH=$OUTPUT_PATH/vocab_test_creation_$RUN_NAME + + +#Train +python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME steps=5 enable_checkpointing=False\ + base_output_directory=$OUTPUT_PATH dataset_path=$DATASET_PATH tokenizer_path=$VOCAB_PATH + +python3 end_to_end/eval_assert.py vocab_creation $VOCAB_PATH diff --git a/maxtext-setup/maxtext/getting_started/Run_Gemma.md b/maxtext-setup/maxtext/getting_started/Run_Gemma.md new file mode 100644 index 0000000000000000000000000000000000000000..6ca618acb60e415a1c255e37d69f38d80b8e1674 --- /dev/null +++ b/maxtext-setup/maxtext/getting_started/Run_Gemma.md @@ -0,0 +1,56 @@ + + +## About Gemma + +Gemma is a family of lightweight, state-of-the art open models built from research and technology that we used to create the Gemini models. To get started on decoding and finetuning of Gemma, you will first need to download weights from [kaggle](https://www.kaggle.com/models/google/gemma?rvi=1) + +Following commands will let you download Gemma-2B model weights along with its tokenizer, convert the orbax checkpoints to be compatible with MaxText and upload it to a GCS bucket. \ +Values for environment variables $KAGGLE_USERNAME and $KAGGLE_KEY can be set using your kaggle account's [API credentials](https://github.com/Kaggle/kaggle-api?tab=readme-ov-file#api-credentials). \ +Please use seperate GCS buckets for uploading model weights from kaggle ($MODEL_BUCKET) and MaxText compatible weights ($CHKPT_BUCKET). +``` +wget https://www.kaggle.com/api/v1/models/google/gemma/maxtext/2b/1/download --user=$KAGGLE_USERNAME --password=$KAGGLE_KEY --auth-no-challenge +# Extract downloaded model +tar -xf download +# export variables $CHKPT_BUCKET and $MODEL_BUCKET which are google cloud buckets to store weights +gsutil -m cp -r 2b/* $CHKPT_BUCKET/2b +gsutil -m cp tokenizer.model $CHKPT_BUCKET/tokenizer.model + +python MaxText/convert_gemma_chkpt.py --base_model_path $CHKPT_BUCKET/2b --maxtext_model_path $MODEL_BUCKET/2b --model_size 2b +``` + +### Run `decode.py`. + +``` +python MaxText/decode.py MaxText/configs/base.yml tokenizer_path=$CHKPT_BUCKET/tokenizer.model load_parameters_path=$MODEL_BUCKET/{MODEL_VARIATION}/0/items per_device_batch_size=1 run_name=runner_$(date +%Y-%m-%d-%H-%M) max_prefill_predict_length=8 max_target_length=64 dataset_type=synthetic steps=10 async_checkpointing=false attention=dot_product model_name=gemma-2b prompt="Kaggle is good for" +``` + +### MaxText supports fine-tuning with high performance. + +Command for training Gemma-2b from scratch on 1 slice of v5e-256. +``` +python MaxText/train.py MaxText/configs/base.yml base_output_directory=$BASE_OUTPUT_DIR model_name=gemma-2b dataset_path=$DATASET_PATH enable_checkpointing=false tokenizer_path=$CHKPT_BUCKET/tokenizer.model steps=10 ici_fsdp_transpose_parallelism=16 per_device_batch_size=2 remat_policy=minimal max_target_length=8192 +``` + +### Performance + +Model Flop utilization for training on v5e and v5p TPUs. + + +| Model | v5e-256 (bf16) | v5p-128 (bf16) | v5e-256 (int8) | v5p-128 (int8) | +| -------- | -------------- | -------------- | -------------- | -------------- | +| Gemma-2b | 58.21% | 55.36% | 64.68% | 67.80% | +| Gemma-7b | 57.70% | 60.16% | 70.31% | 70.12% | diff --git a/maxtext-setup/maxtext/getting_started/Run_MaxText_via_multihost_job.md b/maxtext-setup/maxtext/getting_started/Run_MaxText_via_multihost_job.md new file mode 100644 index 0000000000000000000000000000000000000000..309f321d6ca00b86aff1f790065dc2ded2a999aa --- /dev/null +++ b/maxtext-setup/maxtext/getting_started/Run_MaxText_via_multihost_job.md @@ -0,0 +1,72 @@ + + +## Getting Started: `multihost_job.py` - Production Jobs On Multiple Slices + +The workflow using `multihost_job.py` is optimized for long running experiments, providing resiliency against hardware failure and avoiding long running ssh connections. Its latency is much higher than `multihost_runner.py` because it needs to provision new capacity each time. The `multihost_job.py` script ends once the request to create the TPUs is issued. Logs are written both to gcloud in real time and also sent to GCS at the end of the job. + +The `multihost_job.py` script: + +* Copies your code to your GCS bucket +* Spins up specified TPU VM(s) via CQR +* Directs the TPU's to download then run that code. Because this logic is within the CQR's startup script, if there hardware is interrupted, the job will be rescheduled and resumed. +* Logs to gcloud, and additionally sends the logs to GCS at the job end +* Delete the TPUs and QR at the end of the job. + +1. Choose a directory on your runner machine to develop and clone MaxText into. The runner machine can +either be a TPUVM or not. If your runner machine is a TPUVM, it needs service account roles that grant it permission to create queued resources and has write access to GCS, such as the `TPU ADMIN` and `STORAGE ADMIN` roles. Clone MaxText, and cd into the root of the repo. + +2. Set your project, zone. + Set your gcloud config, see https://cloud.google.com/sdk/gcloud/reference/config for more. + ``` + PROJECT= + ``` + + ``` + ZONE= + ``` + + ``` + gcloud config set project $PROJECT + gcloud config set compute/zone $ZONE + ``` + +3. Link to a GCS bucket. + Create a bucket if you don't already have one, see: https://cloud.google.com/storage/docs/creating-buckets for instructions to create one. Once you've identified your bucket: + + ``` + BUCKET_NAME= + ``` + +4. Run your training job. + + *** IMPORTANT *** `multihost_job` creates a request for new capacity for each run! You cannot use this tool on existing capacity, instead we recommend `multihost_runner` for this purpose. + + Choose the number of nodes (we use 2 below, but you may customize this and other feature of your TPU(s)) + ``` + NODE_COUNT=2 + ``` + ``` + RUN_NAME=$YOUR_JOB_NAME # You may set this to any unique name for a fresh run. + python3 multihost_job.py --NUM_SLICES=$NODE_COUNT --RUN_NAME=$RUN_NAME --BUCKET_NAME=$BUCKET_NAME --CQR_EXTRA_ARGS="--reserved" --COMMAND="bash setup.sh && python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME" + ``` + + We tell `multihost_job` to target the `reserved` pool by by including `--reserved` as extra arguments to the CQR request, but you may instead target the `on-demand` pool by removing the `--CQR_EXTRA_ARGS` flag (on-demand is default), or the pre-emptible pool with `--CQR_EXTRA_ARGS="--best-effort"`, which may be necessary if your reservation is full. + +5. View the job's logs in cloud logging. + + The link to your job's cloud logging is printed at the end of `multihost_job` output. Additionally logs are saved to GCS when your job finishes, and this bucket's URL is also printed by `multihost_job`. + diff --git a/maxtext-setup/maxtext/getting_started/Run_MaxText_via_multihost_runner.md b/maxtext-setup/maxtext/getting_started/Run_MaxText_via_multihost_runner.md new file mode 100644 index 0000000000000000000000000000000000000000..14b215f8e1fee7ec7b845c9f7f54a6a494320df9 --- /dev/null +++ b/maxtext-setup/maxtext/getting_started/Run_MaxText_via_multihost_runner.md @@ -0,0 +1,100 @@ + + +## Getting Started: `multihost_runner.py` - Quick Experiments on Multiple Hosts (or Multiple Slices) + +This workflow using `multihost_runner.py` is optimized for quick experiments, repeatedly re-using the same TPUs. Because the `multihost_runner.py` script depends on long-lived `ssh` connections, we do not recommend it for any long-running jobs. + +We call the `runner` machine the one that `multihost_runner.py` is called from. This script will `ssh` into TPUVM `worker` machines that are found from the `--TPU_PREFIX` flag, and must be different than the runner machine. +If the runner machine is a cloud VM, it must be in the same project as the workers. + +The `multihost_runner.py` script: +* Distributes your code by recursively copying the current state of the chosen directory to multiple worker TPUVM. +* Runs the code on the workers +* Logs and monitors the processes' error statuses and brings the logs back to the runner machine. + +Although there are several steps below, most are for the initial setup. Once setup you can continually make changes to your code and re-run your code with only step 5. + +1. Choose a directory on your runner machine to develop and clone MaxText into. The runner machine can +either be a TPUVM or not, but it cannot be one of the workers. If your runner machine is a TPUVM, it needs service account roles that grant it permission to create queued resources and ssh into them, such as the `TPU ADMIN` role. Clone MaxText, and cd into the root of the repo. + +2. Set your project, zone, and ssh keys. + + Set your gcloud config, see https://cloud.google.com/sdk/gcloud/reference/config for more. + ``` + PROJECT= + ``` + ``` + ZONE= + ``` + ``` + gcloud config set project $PROJECT + gcloud config set compute/zone $ZONE + ``` + + Create ssh keys for gcloud, we recommend leaving a blank password (hit enter twice after running the below command). If you are prompted that the the file already exists you can choose not to overwrite by selecting "n". + ``` + ssh-keygen -f ~/.ssh/google_compute_engine + ``` + +3. Create your instances via Queued Resource (QR). + Choose names for your TPUs and QR: + ``` + TPU_PREFIX=$YOUR_TPU_NAME # Use new names when you create new TPUs + QR_ID=$TPU_PREFIX # Convenient to re-use the node names, but can be different + ``` + Choose the number of nodes (we use 2 below, but you may customize this and other feature of your TPU(s)) + ``` + NODE_COUNT=2 + ``` + Create a multislice environment of nodes using create queued resources + ``` + gcloud alpha compute tpus queued-resources create $QR_ID --accelerator-type=v4-8 --runtime-version=tpu-ubuntu2204-base --node-count=$NODE_COUNT --node-prefix=$TPU_PREFIX --reserved + ``` + We target the `reserved` pool above, but you may instead target the `on-demand` pool by omitting this flag, + or target pre-emptible capacity with the `--best-effort` flag, which may be necessary if your reservation is full. + + You have to wait for the QR to become `ACTIVE` (as opposed to `ACCEPTED` or `PROVISIONING`) which corresponds to the worker nodes becoming `READY` (as opposed to `CREATING`). This may take a minute or two and can be checked via + ``` + gcloud alpha compute tpus queued-resources list --filter=$QR_ID + ``` +4. Install dependencies. + Install the dependencies of `train.py` on each worker using `multihost_runner.py`: + ``` + python3 multihost_runner.py --TPU_PREFIX=$TPU_PREFIX --COMMAND="bash setup.sh" + ``` + If you are running the `multihost_runner.py` script from a TPUVM, you will need to set `--INTERNAL_IP=true`. + +5. Run your training job. + + Set a RUN_NAME for your job: + ``` + RUN_NAME=$YOUR_JOB_NAME # You may set this to any unique name for a fresh run. + ``` + Set config values for `base_output_directory` and `dataset_path` in `configs/base.yml` if not set already. + ``` + python3 multihost_runner.py --TPU_PREFIX=$TPU_PREFIX --COMMAND="python3 MaxText/train.py MaxText/configs/base.yml run_name=$RUN_NAME" + ``` + If you are running the `multihost_runner.py` script from a TPUVM, you will need to set `--INTERNAL_IP=true`. + +6. Clean up TPUs and QR when finished. + + ``` + gcloud alpha compute tpus queued-resources delete $QR_ID --force --async + ``` + + The `--force` flag deletes both the queued resources and the TPU VMs, without it only a `SUSPENDED` queued resource whose TPUs have already been deleted can itself be deleted. We highly recommend the `--async` flag since deleting the TPUs and QR will take a minute or two. + diff --git a/maxtext-setup/maxtext/getting_started/Run_MaxText_via_xpk.md b/maxtext-setup/maxtext/getting_started/Run_MaxText_via_xpk.md new file mode 100644 index 0000000000000000000000000000000000000000..ef6e3e2006cd30f5ee567eb293dc985f8308bfad --- /dev/null +++ b/maxtext-setup/maxtext/getting_started/Run_MaxText_via_xpk.md @@ -0,0 +1,119 @@ + + + +# How to run MaxText with XPK? + +This document focuses on steps required to setup XPK on TPU VM and assumes you have gone through the [README](https://github.com/google/xpk/blob/main/README.md) to understand XPK basics. + +## Steps to setup XPK on TPU VM + +* Verify you have these permissions for your account or service account + + Storage Admin \ + Kubernetes Engine Admin + +* gcloud is installed on TPUVMs using the snap distribution package. Install kubectl using snap +```shell +sudo snap install kubectl --classic +``` +* Install `gke-gcloud-auth-plugin` +```shell +echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list + +curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add - + +sudo apt update && sudo apt-get install google-cloud-sdk-gke-gcloud-auth-plugin +``` + +* Authenticate gcloud installation by running this command and following the prompt +``` +gcloud auth login +``` + +* Run this command to configure docker to use docker-credential-gcloud for GCR registries: +``` +gcloud auth configure-docker +``` + +* Test the installation by running +``` +docker run hello-world +``` + +* If getting a permission error, try running +``` +sudo usermod -aG docker $USER +``` +after which log out and log back in to the machine. + +## Build Docker Image for Maxtext + +1. Git clone maxtext locally + + ```shell + git clone https://github.com/google/maxtext.git + cd maxtext + ``` +2. Build local Maxtext docker image + + This only needs to be rerun when you want to change your dependencies. This image may expire which would require you to rerun the below command + + ```shell + # Default will pick stable versions of dependencies + bash docker_build_dependency_image.sh + ``` +3. After building the dependency image `maxtext_base_image`, xpk can handle updates to the working directory when running `xpk workload create` and using `--base-docker-image`. + + See details on docker images in xpk here: https://github.com/google/xpk/blob/main/README.md#how-to-add-docker-images-to-a-xpk-workload + + __Using xpk to upload image to your gcp project and run Maxtext__ + + ```shell + gcloud config set project $PROJECT_ID + gcloud config set compute/zone $ZONE + + # See instructions in README.me to create below buckets. + BASE_OUTPUT_DIR=gs://output_bucket/ + DATASET_PATH=gs://dataset_bucket/ + + # Install xpk + pip install xpk + + # Make sure you are still in the maxtext github root directory when running this command + xpk workload create \ + --cluster ${CLUSTER_NAME} \ + --base-docker-image maxtext_base_image \ + --workload ${USER}-first-job \ + --tpu-type=v5litepod-256 \ + --num-slices=1 \ + --command "python3 MaxText/train.py MaxText/configs/base.yml base_output_directory=${BASE_OUTPUT_DIR} dataset_path=${DATASET_PATH} steps=100 per_device_batch_size=1" + ``` + + __Using [xpk github repo](https://github.com/google/xpk.git)__ + + ```shell + git clone https://github.com/google/xpk.git + + # Make sure you are still in the maxtext github root directory when running this command + python3 xpk/xpk.py workload create \ + --cluster ${CLUSTER_NAME} \ + --base-docker-image maxtext_base_image \ + --workload ${USER}-first-job \ + --tpu-type=v5litepod-256 \ + --num-slices=1 \ + --command "python3 MaxText/train.py MaxText/configs/base.yml base_output_directory=${BASE_OUTPUT_DIR} dataset_path=${DATASET_PATH} steps=100 per_device_batch_size=1" + ``` diff --git a/maxtext-setup/maxtext/gke/gpu/maxtext_chart/Chart.yaml b/maxtext-setup/maxtext/gke/gpu/maxtext_chart/Chart.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bbe13883f31bcec027b10da5e90f9ceae462e07f --- /dev/null +++ b/maxtext-setup/maxtext/gke/gpu/maxtext_chart/Chart.yaml @@ -0,0 +1,24 @@ +apiVersion: v2 +name: maxtext_chart +description: A Helm chart for Maxtext GPU workload + +# A chart can be either an 'application' or a 'library' chart. +# +# Application charts are a collection of templates that can be packaged into versioned archives +# to be deployed. +# +# Library charts provide useful utilities or functions for the chart developer. They're included as +# a dependency of application charts to inject those utilities and functions into the rendering +# pipeline. Library charts do not define any templates and therefore cannot be deployed. +type: application + +# This is the chart version. This version number should be incremented each time you make changes +# to the chart and its templates, including the app version. +# Versions are expected to follow Semantic Versioning (https://semver.org/) +version: 0.1.0 + +# This is the version number of the application being deployed. This version number should be +# incremented each time you make changes to the application. Versions are not expected to +# follow Semantic Versioning. They should reflect the version the application is using. +# It is recommended to use it with quotes. +appVersion: "1.16.0" diff --git a/maxtext-setup/maxtext/gke/gpu/maxtext_chart/templates/maxtext.yaml b/maxtext-setup/maxtext/gke/gpu/maxtext_chart/templates/maxtext.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5ab88f38cb92d4f7f6fdec0509bd4fcc620a64f1 --- /dev/null +++ b/maxtext-setup/maxtext/gke/gpu/maxtext_chart/templates/maxtext.yaml @@ -0,0 +1,144 @@ +{{- $requiredVar := .Values.cluster.nNodes | required ".Values.cluster.nNodes is required" -}} +{{- $requiredVar := .Values.cluster.nodePool | required ".Values.cluster.nodePool is required" -}} +{{- $requiredVar := .Values.workload.image | required ".Values.image is required" -}} +apiVersion: v1 +kind: Service +metadata: + name: "maxtext-leader-{{$.Release.Name}}" +spec: + selector: + name: "maxtext-leader-{{$.Release.Name}}" + clusterIP: None + ports: + - name: maxtext-leader + port: 6002 +--- +{{$node_count := .Values.cluster.nNodes | int}} +# This needs to be updated to allow uneven distribution of nodes to SBs +{{- $root := . -}} +{{range $node_index, $element := until $node_count}} +apiVersion: v1 +kind: Pod +metadata: + name: maxtext-{{$.Release.Name}}-pod{{$node_index}} + {{if eq $node_index 0}} + labels: + name: maxtext-leader-{{$.Release.Name}} + {{end}} +spec: + hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet + hostname: maxtext-pod{{$node_index}} + subdomain: maxtext-{{$.Release.Name}} + serviceAccountName: "default" + restartPolicy: Never + affinity: + nodeAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + nodeSelectorTerms: + - matchExpressions: + - key: cloud.google.com/gke-accelerator + operator: Exists + - key: cloud.google.com/gke-nodepool + operator: In + values: [{{$.Values.cluster.nodePool}}] + tolerations: + - operator: "Exists" + key: nvidia.com/gpu + volumes: + - name: nvidia-install-dir-host + hostPath: + path: /home/kubernetes/bin/nvidia/lib64 + - name: tcpd-socket + hostPath: + path: /run/tcpx + - name: shared-memory + emptyDir: + medium: "Memory" + sizeLimit: 200Gi + - name: workload-terminated-volume + emptyDir: {} + - name: tcpx-nccl-plugin-volume + emptyDir: {} + {{if eq $root.Values.network.useTcpx "yes"}} + initContainers: + - name: tcpx-nccl-plugin-installer + image: {{$root.Values.network.ncclPlugin}} + imagePullPolicy: Always + volumeMounts: + - name: tcpx-nccl-plugin-volume + mountPath: /var/lib/tcpx + resources: + requests: + cpu: 150m + command: + - /bin/sh + - -c + - | + /scripts/container_entry.sh install --install-nccl + {{end}} + containers: + {{if eq $root.Values.network.useTcpx "yes"}} + - name: tcpd-daemon + image: {{$root.Values.network.rxdmContainer}} + imagePullPolicy: Always + command: + - "bash" + - "-c" + - | + /tcpgpudmarxd/build/app/tcpgpudmarxd --gpu_nic_preset a3vm --gpu_shmem_type fd --setup_param "--verbose 128 2 0" & + while [ ! -e "/usr/share/maxtext/workload_terminated" ]; do sleep 10; echo "sleeping"; done + securityContext: + privileged: true + volumeMounts: + - name: nvidia-install-dir-host + mountPath: /usr/local/nvidia/lib64 + - name: tcpd-socket + mountPath: /tmp + - name: workload-terminated-volume + mountPath: /usr/share/maxtext + env: + - name: LD_LIBRARY_PATH + value: /usr/local/nvidia/lib64 + {{end}} + - name: maxtext + image: {{$root.Values.workload.image}} + imagePullPolicy: Always + securityContext: + privileged: true + env: + - name: NNODES + value: "{{$node_count}}" + - name: NODE_RANK + value: "{{ $node_index }}" + - name: USE_GPUDIRECT_TCPX + value: "{{$root.Values.network.useTcpx}}" + - name: GPUS_PER_NODE + value: "8" + - name: JAX_COORDINATOR_ADDRESS + value: "maxtext-leader-{{$.Release.Name}}" + - name: JAX_COORDINATOR_PORT + value: "{{$root.Values.workload.port}}" + - name: RUN_NAME + value: "{{$root.Values.workload.runName}}" + - name: LD_LIBRARY_PATH + value: /usr/local/nvidia/lib64 + volumeMounts: + - name: nvidia-install-dir-host + mountPath: /usr/local/nvidia/lib64 + - name: tcpx-nccl-plugin-volume + mountPath: /usr/local/tcpx + - name: tcpd-socket + mountPath: /tmp + - name: shared-memory + mountPath: /dev/shm + resources: + limits: + nvidia.com/gpu: !!int 8 + command: + - /bin/sh + - -c + - | + cd /deps && bash gke/gpu/start_training.sh +--- +{{end}} \ No newline at end of file diff --git a/maxtext-setup/maxtext/gke/gpu/maxtext_chart/values.yaml b/maxtext-setup/maxtext/gke/gpu/maxtext_chart/values.yaml new file mode 100644 index 0000000000000000000000000000000000000000..beaa962729ca7a837b2f6405bb9bc0f2cdca5fee --- /dev/null +++ b/maxtext-setup/maxtext/gke/gpu/maxtext_chart/values.yaml @@ -0,0 +1,11 @@ +cluster: + nNodes: 2 # Configure the number of nodes + nodePool: "" # Configure NodePool Information +network: + useTcpx: "yes" + ncclPlugin: us-docker.pkg.dev/gce-ai-infra/gpudirect-tcpx/nccl-plugin-gpudirecttcpx-dev:v3.1.6_2023_10_06 + rxdmContainer: us-docker.pkg.dev/gce-ai-infra/gpudirect-tcpx/tcpgpudmarxd-dev:v2.0.9 +workload: + image: "" # Configure Image Name + port: 6002 + runName: "" # Configure Run Name diff --git a/maxtext-setup/maxtext/gke/gpu/start_training.sh b/maxtext-setup/maxtext/gke/gpu/start_training.sh new file mode 100644 index 0000000000000000000000000000000000000000..315b1e2d9d3d7e5cb4a7eb58219986e615a1166d --- /dev/null +++ b/maxtext-setup/maxtext/gke/gpu/start_training.sh @@ -0,0 +1,135 @@ +#! /bin/bash +set -e +set -u +set -o pipefail + +: "${NNODES:?Must set NNODES}" +: "${NODE_RANK:?Must set NODE_RANK}" +: "${JAX_COORDINATOR_PORT:?Must set JAX_COORDINATOR_PORT}" +: "${JAX_COORDINATOR_ADDRESS:?Must set JAX_COORDINATOR_ADDRESS}" +: "${GPUS_PER_NODE:?Must set GPUS_PER_NODE}" +: "${RUN_NAME:?Must set RUN_NAME}" + + +export GPUS_PER_NODE=$GPUS_PER_NODE +export JAX_COORDINATOR_PORT=$JAX_COORDINATOR_PORT +export JAX_COORDINATOR_ADDRESS=$JAX_COORDINATOR_ADDRESS +export JAX_NUM_PROCESSES=$((NNODES * GPUS_PER_NODE)) + +set_nccl_gpudirect_tcpx_specific_configuration() { + if [[ "$USE_GPUDIRECT_TCPX" == "yes" ]]; then + echo "Using GPUDirect-TCPX" + export NCCL_CROSS_NIC=0 + export NCCL_ALGO=Ring + export NCCL_PROTO=Simple + export NCCL_DEBUG=INFO + export NCCL_NET_GDR_LEVEL=PIX + export NCCL_P2P_PXN_LEVEL=0 + export NCCL_DEBUG_SUBSYS=INIT,GRAPH,ENV,TUNING,NET,VERSION + export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:/usr/local/tcpx/lib64" + export NCCL_GPUDIRECTTCPX_FORCE_ACK=0 + export NCCL_GPUDIRECTTCPX_TX_COMPLETION_NANOSLEEP=1000 + export NCCL_DYNAMIC_CHUNK_SIZE=524288 + export NCCL_P2P_NET_CHUNKSIZE=524288 + export NCCL_P2P_PCI_CHUNKSIZE=524288 + export NCCL_P2P_NVL_CHUNKSIZE=1048576 + export NCCL_NSOCKS_PERTHREAD=4 + export NCCL_SOCKET_NTHREADS=1 + export NCCL_MAX_NCHANNELS=12 + export NCCL_MIN_NCHANNELS=12 + export NCCL_GPUDIRECTTCPX_PROGRAM_FLOW_STEERING_WAIT_MICROS=1000000 + export NCCL_SOCKET_IFNAME=eth0 + export NCCL_GPUDIRECTTCPX_TX_BINDINGS="eth1:8-21,112-125;eth2:8-21,112-125;eth3:60-73,164-177;eth4:60-73,164-177" + export NCCL_GPUDIRECTTCPX_RX_BINDINGS="eth1:22-35,124-139;eth2:22-35,124-139;eth3:74-87,178-191;eth4:74-87,178-191" + export NCCL_GPUDIRECTTCPX_SOCKET_IFNAME=eth1,eth2,eth3,eth4 + export NCCL_GPUDIRECTTCPX_CTRL_DEV=eth0 + export NCCL_NVLS_ENABLE=0 + else + echo "NOT using TCPX" + fi +} + +echo "LD_LIBRARY_PATH ${LD_LIBRARY_PATH}" + +set_nccl_gpudirect_tcpx_specific_configuration + +wait_all_success_or_exit() { + # https://www.baeldung.com/linux/background-process-get-exit-code + local pids=("$@") + while [[ ${#pids[@]} -ne 0 ]]; do + all_success="true" + for pid in "${pids[@]}"; do + code=$(non_blocking_wait "$pid") + if [[ $code -ne 127 ]]; then + if [[ $code -ne 0 ]]; then + echo "PID $pid failed with exit code $code" + exit "$code" + fi + else + all_success="false" + fi + done + if [[ $all_success == "true" ]]; then + echo "All pids succeeded" + break + fi + sleep 5 + done +} +non_blocking_wait() { + # https://www.baeldung.com/linux/background-process-get-exit-code + local pid=$1 + local code=127 # special code to indicate not-finished + if [[ ! -d "/proc/$pid" ]]; then + wait "$pid" + code=$? + fi + echo $code +} + +resolve_coordinator_ip() { + local lookup_attempt=1 + local max_coordinator_lookups=10 + local coordinator_found=false + local coordinator_ip_address="" + + echo "Coordinator Address $JAX_COORDINATOR_ADDRESS" + + while [[ "$coordinator_found" = false && $lookup_attempt -le $max_coordinator_lookups ]]; do + coordinator_ip_address=$(nslookup "$JAX_COORDINATOR_ADDRESS" 2>/dev/null | awk '/^Address: / { print $2 }' | head -n 1) + if [[ -n "$coordinator_ip_address" ]]; then + coordinator_found=true + echo "Coordinator IP address: $coordinator_ip_address" + export JAX_COORDINATOR_IP=$coordinator_ip_address + return 0 + else + echo "Failed to recognize coordinator address $JAX_COORDINATOR_ADDRESS on attempt $lookup_attempt, retrying..." + ((lookup_attempt++)) + sleep 1 + fi + done + + if [[ "$coordinator_found" = false ]]; then + echo "Failed to resolve coordinator address after $max_coordinator_lookups attempts." + return 1 + fi +} + +# HLO dump +export XLA_FLAGS="--xla_dump_to=/tmp/xladump" + +# Resolving coordinator IP +set +e +resolve_coordinator_ip +set -e + +PIDS=() +for ((LOCAL_DEVICE_ID=0; LOCAL_DEVICE_ID <= $((GPUS_PER_NODE - 1)); LOCAL_DEVICE_ID++)); do + PROCESS_ID=$(($GPUS_PER_NODE*$NODE_RANK + $LOCAL_DEVICE_ID)) + LOCAL_DEVICE_ID=$LOCAL_DEVICE_ID PROCESS_ID=$PROCESS_ID python MaxText/train.py MaxText/configs/base.yml hardware=gpu run_name=${RUN_NAME}_$(date +%Y-%m-%d-%H-%M)-${RANDOM} & + PID=$! + PIDS+=($PID) + echo "Launched MaxText/train.py for local_device_id: $LOCAL_DEVICE_ID process_id: $PROCESS_ID and PID $PID" +done + +wait_all_success_or_exit "${PIDS[@]}" diff --git a/maxtext-setup/maxtext/maxtext_dependencies.Dockerfile b/maxtext-setup/maxtext/maxtext_dependencies.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cfc16547db36f623feb1c2bd1ed212dc13079a80 --- /dev/null +++ b/maxtext-setup/maxtext/maxtext_dependencies.Dockerfile @@ -0,0 +1,47 @@ +# Use Python 3.10 as the base image +FROM python:3.10-slim-bullseye + +# Install system dependencies Git, and numactl +RUN apt-get update && apt-get install -y curl gnupg git numactl + +# Install dependencies for adjusting network rto +RUN apt-get update && apt-get install -y iproute2 ethtool lsof + +# Add the Google Cloud SDK package repository +RUN echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list +RUN curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg add - + +# Install the Google Cloud SDK +RUN apt-get update && apt-get install -y google-cloud-sdk + +# Set the default Python version to 3.10 +RUN update-alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.10 1 + +# Set environment variables for Google Cloud SDK and Python 3.10 +ENV PATH="/usr/local/google-cloud-sdk/bin:/usr/local/bin/python3.10:${PATH}" + +ARG MODE +ENV ENV_MODE=$MODE + +ARG JAX_VERSION +ENV ENV_JAX_VERSION=$JAX_VERSION + +ARG LIBTPU_GCS_PATH +ENV ENV_LIBTPU_GCS_PATH=$LIBTPU_GCS_PATH + +ARG DEVICE +ENV ENV_DEVICE=$DEVICE + +RUN mkdir -p /deps + +# Set the working directory in the container +WORKDIR /deps + +# Copy all files from local workspace into docker container +COPY . . +RUN ls . + +RUN echo "Running command: bash setup.sh MODE=$ENV_MODE JAX_VERSION=$ENV_JAX_VERSION LIBTPU_GCS_PATH=${ENV_LIBTPU_GCS_PATH} DEVICE=${ENV_DEVICE}" +RUN bash setup.sh MODE=${ENV_MODE} JAX_VERSION=${ENV_JAX_VERSION} LIBTPU_GCS_PATH=${ENV_LIBTPU_GCS_PATH} DEVICE=${ENV_DEVICE} + +WORKDIR /app diff --git a/maxtext-setup/maxtext/maxtext_gpu_dependencies.Dockerfile b/maxtext-setup/maxtext/maxtext_gpu_dependencies.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..242435b29c12022977f4b3ef8ab8964af3b11cdd --- /dev/null +++ b/maxtext-setup/maxtext/maxtext_gpu_dependencies.Dockerfile @@ -0,0 +1,43 @@ +FROM ghcr.io/nvidia/jax:base + +# Install dependencies for adjusting network rto +RUN apt-get update && apt-get install -y iproute2 ethtool lsof + +# Install DNS util dependencies +RUN apt-get install -y dnsutils + +# Add the Google Cloud SDK package repository +RUN echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list +RUN curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg add - + +# Install the Google Cloud SDK +RUN apt-get update && apt-get install -y google-cloud-sdk + +# Set environment variables for Google Cloud SDK +ENV PATH="/usr/local/google-cloud-sdk/bin:${PATH}" + +# Upgrade libcusprase to work with Jax +RUN apt-get update && apt-get install -y libcusparse-12-3 + +ARG MODE +ENV ENV_MODE=$MODE + +ARG JAX_VERSION +ENV ENV_JAX_VERSION=$JAX_VERSION + +ARG DEVICE +ENV ENV_DEVICE=$DEVICE + +RUN mkdir -p /deps + +# Set the working directory in the container +WORKDIR /deps + +# Copy all files from local workspace into docker container +COPY . . +RUN ls . + +RUN echo "Running command: bash setup.sh MODE=$ENV_MODE JAX_VERSION=$ENV_JAX_VERSION DEVICE=${ENV_DEVICE}" +RUN bash setup.sh MODE=${ENV_MODE} JAX_VERSION=${ENV_JAX_VERSION} DEVICE=${ENV_DEVICE} + +WORKDIR /app diff --git a/maxtext-setup/maxtext/maxtext_libtpu_path.Dockerfile b/maxtext-setup/maxtext/maxtext_libtpu_path.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9443db05c2986f290dcede03bd7da3faf18d8554 --- /dev/null +++ b/maxtext-setup/maxtext/maxtext_libtpu_path.Dockerfile @@ -0,0 +1,8 @@ +ARG BASEIMAGE=maxtext_base_image +FROM $BASEIMAGE + +#FROM maxtext_base_image +# Set the TPU_LIBRARY_PATH +ENV TPU_LIBRARY_PATH='/root/custom_libtpu/libtpu.so' + +WORKDIR /app \ No newline at end of file diff --git a/maxtext-setup/maxtext/maxtext_runner.Dockerfile b/maxtext-setup/maxtext/maxtext_runner.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..15106dd89db2b54c51a61813ff10f48933a91814 --- /dev/null +++ b/maxtext-setup/maxtext/maxtext_runner.Dockerfile @@ -0,0 +1,12 @@ +ARG BASEIMAGE=maxtext_base_image +FROM $BASEIMAGE + +#FROM maxtext_base_image + +# Set the working directory in the container +WORKDIR /app + +# Copy all files from local workspace into docker container +COPY . . + +WORKDIR /app \ No newline at end of file diff --git a/maxtext-setup/maxtext/multihost_job.py b/maxtext-setup/maxtext/multihost_job.py new file mode 100644 index 0000000000000000000000000000000000000000..04be91729ba31c4980f0b1780f7523ac73e1502c --- /dev/null +++ b/maxtext-setup/maxtext/multihost_job.py @@ -0,0 +1,359 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +""" Script to run a productionized job in a multislice/multihost environment + ***** IMPORTANT ***** +This script provisions new TPUs! You cannot run jobs on existing TPUs with this script, +we recommend trying multihost_runner instead for this purpose. In addition you must include all +of your installation commands inside of the --COMMAND arg, e.g. --COMMAND="bash setup.sh && python3 train.py" + +This script: + 1) Creates specified TPU(s) + 2) Loads your scripts onto each TPU + 3) Runs your job on each TPU + 4) Logs the output of the job in real time to cloud logging + 5) Stores a copy of the logs and zipped code in GCS at the job's end + 6) Deletes the TPUs and QR +Example usages: + Minimal customization, assuming runner.sh lives in present working directory: + python3 multihost_job.py --COMMAND="bash runner.sh" --BUCKET_NAME= + + Maximal customization, assuming runner.sh lives in path/to/dir + python3 multihost_job.py --COMMAND="bash runner.sh" --BUCKET_NAME= --BUCKET_DIR=job-log-directory \ + --SCRIPT_DIR=path/to/dir --PROJECT= --ZONE= \ + --VERSION=tpu-ubuntu2204-base --TPU_TYPE=v4-8 --NUM_SLICES=2 --RUN_NAME=$USER-run-job +Common issues: + You must have local write permissions to BUCKET_NAME. The allocated TPUVMs must also have read permissions to this + bucket, which is granted through service account roles, such as Storage Object Admin. +""" +import argparse +import sys +import subprocess +from datetime import datetime +import os +import shutil + + + +def get_project(): + completed_command = subprocess.run(["gcloud", "config", "get", "project"], check=True, capture_output=True) + project_outputs = completed_command.stdout.decode().strip().split('\n') + if len(project_outputs) < 1 or project_outputs[-1]=='': + sys.exit("You must specify the project in the PROJECT flag or set it with 'gcloud config set project '") + return project_outputs[-1] # The project name lives on the last line of the output + +def get_zone(): + completed_command = subprocess.run(["gcloud", "config", "get", "compute/zone"], check=True, capture_output=True) + zone_outputs = completed_command.stdout.decode().strip().split('\n') + if len(zone_outputs) < 1 or zone_outputs[-1]=='': + sys.exit("You must specify the zone in the ZONE flag or set it with 'gcloud config set compute/zone '") + return zone_outputs[-1] # The zone name lives on the last line of the output + +def get_run_name(): + now = datetime.now() + return os.getlogin() + "-" + now.strftime("%Y-%m-%d-%H-%M-%S") + +def normalize_gcs_bucket_name(args): + """ Remove the gs:// from bucket_name if passed.""" + if len(args.BUCKET_NAME) > 5 and args.BUCKET_NAME[0:5]=="gs://": + args.BUCKET_NAME=args.BUCKET_NAME[5:] + return args + +def print_flags(args): + """ Print configuration values after defaults have been filled in. """ + print("Running multihost_job with the following configuration:") + print(f"Project (--PROJECT) = {args.PROJECT}") + print(f"Zone (--ZONE) = {args.ZONE}") + print(f"TPU type (--TPU_TYPE) = {args.TPU_TYPE}") + print(f"TPU runtime version (--VERSION) = {args.VERSION}") + print(f"Number of slices (--NUM_SLICES) = {args.NUM_SLICES}") + print(f"Script dir (--SCRIPT_DIR) = {args.SCRIPT_DIR}") + print(f"Bucket name (--BUCKET_NAME) = {args.BUCKET_NAME}") + print(f"Bucket dir (--BUCKET_DIR) = {args.BUCKET_DIR}") + print(f"Run name (--RUN_NAME) = {args.RUN_NAME}") + print(f"Extra CQR args (--CQR_EXTRA_ARGS) = {args.CQR_EXTRA_ARGS}") + print(f"Command to run (--COMMAND) = {args.COMMAND}") + print(f"Enable Autocheckpoint (--ENABLE_AUTOCHECKPOINT) = {args.ENABLE_AUTOCHECKPOINT}\n") + +def move_script_dir_to_gcs(script_dir, tmp_dir, zip_name, bucket_path): + """ Zip the script directory, cp it to GCS """ + original_working_directory = os.getcwd() + os.chdir(script_dir) # To tar script_dir, it is most convenient to cd there. + + # Zip script directory, storing it in the logging directory. + os.makedirs(tmp_dir, exist_ok=True) + zip_path = os.path.join(tmp_dir, zip_name) + command = ["tar", "--exclude=tmp", "-czf", zip_path, "./"] + subprocess.run(command, check=True) + + # Move zip file to GCS + zip_in_gcs_path = os.path.join(bucket_path, zip_name) + command = ["gsutil", "mv", zip_path, zip_in_gcs_path] + captured_output = subprocess.run(command, check=True, capture_output=True) + + # Cleanup + os.chdir(original_working_directory) + + return captured_output + +def run_create_resources(startup_script_file, args): + """ Run the Create Queued Resources (CQR) request """ + # pylint: disable=line-too-long + command = fr'gcloud alpha compute tpus queued-resources create {args.RUN_NAME} --accelerator-type={args.TPU_TYPE} --runtime-version={args.VERSION} --project={args.PROJECT} --zone={args.ZONE}' + if args.NUM_SLICES > 1: + command = command + f' --node-prefix={args.RUN_NAME} --node-count={args.NUM_SLICES}' + else: + command = command + f' --node-id={args.RUN_NAME}' + + if args.CQR_EXTRA_ARGS: + command = command + ' ' + args.CQR_EXTRA_ARGS + + if args.ENABLE_AUTOCHECKPOINT: + command = command + ' --autocheckpoint-enabled' + + command = command + f' --metadata-from-file=startup-script={startup_script_file}' + + captured_output = subprocess.run(command, check=False, shell=True, capture_output=True) + return captured_output + +def write_startup_script(zip_gcs_path, zip_name, log_name, bucket_path, startup_script_file, args): + """ Write the startup script locally into a file to be passed to the CQR command. """ + startup_script = f"""#!/bin/bash +mkdir -p {args.RUN_NAME} +cd {args.RUN_NAME} +{get_env_command_str(args.NUM_SLICES)} +{setup_ops_str(args.RUN_NAME, log_name)} +sudo python3 -m virtualenv venv +source venv/bin/activate +ulimit -n 100000 +(({download_from_gcs(zip_gcs_path)} +tar xzf {zip_name} +{args.COMMAND}) 2>&1) >> {log_name} +(echo "{finish_status_str()}") >> {log_name} +gsutil cp {log_name} "{bucket_path}/" +(({create_kill_command_str(args)}) 2>&1 ) >> {log_name}""" + + with open(startup_script_file, "w", encoding="utf-8") as f: + f.write(startup_script) + return startup_script + +def get_env_command_str(num_slices): + """ Define environment variables on the TPUS """ + # pylint: disable=line-too-long + env_str = """curl -s 'http://metadata.google.internal/computeMetadata/v1/instance/attributes/tpu-env' -H 'Metadata-Flavor: Google' > /tmp/tpu-env # store the metadata +NODE_ID=$(grep '^NODE_ID' /tmp/tpu-env | cut -d "'" -f 2) +WORKER_ID=$(grep '^WORKER_ID' /tmp/tpu-env | cut -d "'" -f 2) +ZONE=$(grep '^ZONE' /tmp/tpu-env | cut -d "'" -f 2) +PROJECT=$(grep '^CONSUMER_PROJECT_ID' /tmp/tpu-env | cut -d "'" -f 2)""" + if num_slices == 1: + slice_assignment = "SLICE_ID=0" + else: + slice_assignment = """SLICE_ID=$(grep '^MEGASCALE_SLICE_ID' /tmp/tpu-env | cut -d "'" -f 2)""" + return env_str + "\n" + slice_assignment + +def finish_status_str(): + # pylint: disable=line-too-long + return """multihost_job finished main command on slice $SLICE_ID worker $WORKER_ID at $(date "+%Y-%m-%d %H:%M:%S") UTC with exit status $?. +This worker will immediately send its logs to GCS.""" + +def create_kill_command_str(args): + # pylint: disable=line-too-long + return f"""if [[ $SLICE_ID -eq 0 && $WORKER_ID -eq 0 ]]; then + echo "This worker (slice 0 worker 0) will wait 10 minutes before tearing down the job to allow other workers to gracefully exit." + sleep 600 + gcloud alpha compute tpus queued-resources delete {args.RUN_NAME} --force --quiet --project={args.PROJECT} --zone={args.ZONE} + fi""" + +def download_from_gcs(zip_gcs_path): + return f""" + echo "{write_download_from_gcs_sh(zip_gcs_path)}" > download_from_gcs.sh + bash download_from_gcs.sh + """ + +def write_download_from_gcs_sh(zip_gcs_path): + # pylint: disable=anomalous-backslash-in-string + return f"""GCS_READ_SUCCESS=0 +while [ \$GCS_READ_SUCCESS -eq 0 ] +do + {{ # try + gsutil cp {zip_gcs_path} . && + echo 'Code download from GCS successful!' && GCS_READ_SUCCESS=1 + }} || {{ # catch + echo 'Failed to read GCS via gsutil, trying again' + sleep 10 + }} +done""" + +def setup_ops_str(run_name, log_name): + return f""" + echo "{install_ops_script_str(run_name, log_name)}" > install_ops_wait_dpkg.sh + bash install_ops_wait_dpkg.sh & + """ + +def install_ops_script_str(run_name, log_name): + # pylint: disable=anomalous-backslash-in-string + return f"""OPS_FILE=/etc/google-cloud-ops-agent/config.yaml + if ! test -f \$OPS_FILE; + then + curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh + downloaded=0 + while [ \$downloaded -eq 0 ] + do + pid=\$(sudo lsof /var/lib/dpkg/lock-frontend | awk \\"END{{print \$2}}\\") + if [[ ! -z \"\${{pid}}\" ]] + then + sleep 10 + else + sudo bash add-google-cloud-ops-agent-repo.sh --also-install + downloaded=1 + fi + done + fi + sudo chmod 777 /etc/google-cloud-ops-agent/config.yaml + sudo echo \\"{create_ops_config_str(run_name, log_name)}\\" >> /etc/google-cloud-ops-agent/config.yaml + sudo service google-cloud-ops-agent restart +""" + +def create_ops_config_str(run_name, log_name): + return f"""logging: + receivers: + {run_name}_log: + type: files + include_paths: + - /{run_name}/{log_name} + record_log_file_path: true + service: + pipelines: + default_pipeline: + receivers: [{run_name}_log]""" + +def google_cloud_logging_url(run_name, project): + # pylint: disable=line-too-long + return f"https://console.cloud.google.com/logs/query;query=resource.type%3D%22gce_instance%22%20AND%0Alog_id%2528%22{run_name}_log%22%2529;?project={project}" + + +def google_cloud_logging_single_host_url(run_name, project): + # pylint: disable=line-too-long + return f"https://console.cloud.google.com/logs/query;query=resource.type%3D%22gce_instance%22%20AND%0Alog_id%2528%22{run_name}_log%22%2529%20AND%0Alabels.%22agent.googleapis.com%2Flog_file_path%22%3D%20%22%2F{run_name}%2Fmain_command_log_slice_0_worker_0%22;?project={project}" + +def gcs_bucket_url(bucket_name, bucket_dir, project): + bucket_path = os.path.join(bucket_name, bucket_dir) + return f"https://console.cloud.google.com/storage/browser/{bucket_path}?project={project}" + +################### Main ################### +def main(raw_args=None) -> None: + ##### Define flags ##### + parser = argparse.ArgumentParser(description='TPU configuration options') + parser.add_argument('--TPU_TYPE', type=str, default='v4-8', + help='The type of the TPU') + parser.add_argument('--VERSION', type=str, default='tpu-ubuntu2204-base', + help='The runtime version of the TPU') + parser.add_argument('--NUM_SLICES', type=int, default=2, + help='The number of slices to run the job on') + parser.add_argument('--SCRIPT_DIR', type=str, default=os.getcwd(), + help='The local location of the directory to copy to the TPUs and run the main command from. \ + Defaults to current working directory.') + parser.add_argument('--COMMAND', type=str, default=None, required=True, + help='Main command to run on each TPU. \ + This command is run from a copied version of SCRIPT_DIR on each TPU worker. \ + You must include your dependency installations here, \ + e.g. --COMMAND=\'bash setup.sh && python3 train.py\'') + parser.add_argument('--BUCKET_NAME', type=str, default=None, required=True, + help='Name of GCS bucket, e.g. my-bucket') + parser.add_argument('--BUCKET_DIR', type=str, default="", + help='Directory within the GCS bucket, can be None, e.g. my-dir') + parser.add_argument('--PROJECT', type=str, default=None, + help='GCE project name, defaults to gcloud config project') + parser.add_argument('--ZONE', type=str, default=None, + help='GCE zone, e.g. us-central2-b, defaults to gcloud config compute/zone') + parser.add_argument('--RUN_NAME', type=str, default=None, + help='Run name used for temporary files, defaults to timestamp.') + parser.add_argument('--CQR_EXTRA_ARGS', type=str, default=None, + help='Additional arguments to be passed verbatim to the CQR request, e.g. \ + --CQR_EXTRA_ARGS="--reserved --service-account=my-service-account-email-address') + parser.add_argument('--ENABLE_AUTOCHECKPOINT', type=bool, default=False, + help='Whether to enable the Autocheckpoint feature') + args = parser.parse_args(raw_args) + + + print("\nStarting multihost_job...\n", flush=True) + + #### Parse flags #### + if not args.PROJECT: + args.PROJECT = get_project() + if not args.ZONE: + args.ZONE = get_zone() + if not args.RUN_NAME: + args.RUN_NAME = get_run_name() # Used for QR name, TPU_PREFIX, logging file, and tmp json file. + args = normalize_gcs_bucket_name(args) + + print_flags(args) + + ##### Step 1: Zip code and move it to GCS ##### + tmp_dir_relative_to_script = os.path.join("tmp", args.RUN_NAME, "") + tmp_dir = os.path.join(args.SCRIPT_DIR, tmp_dir_relative_to_script) + zip_name = "script_dir_zip_" + args.RUN_NAME + ".tar.gz" + bucket_dir = os.path.join(args.BUCKET_DIR, args.RUN_NAME) + bucket_path = os.path.join(f"gs://{args.BUCKET_NAME}", bucket_dir) + startup_script_file = os.path.join(tmp_dir, "startup_script.txt") + + print(f"Moving {args.SCRIPT_DIR} to {bucket_path}...") + captured_output = move_script_dir_to_gcs(args.SCRIPT_DIR, tmp_dir_relative_to_script, zip_name, bucket_path) + if captured_output.returncode != 0: + print("\n\n Moving code to GCS failed") + print(f"Running 'gsutil mv zip {bucket_path}' failed with error: ") + print(captured_output.stderr.decode()) + print("\nYou may need to run 'gcloud auth login'") + return -1 + print("Move successful!\n") + + #### Step 2: Run the CQR command #### + log_name = "main_command_log_slice_${SLICE_ID}_worker_${WORKER_ID}" + zip_gcs_path = os.path.join(bucket_path, zip_name) + write_startup_script(zip_gcs_path, zip_name, log_name, bucket_path, startup_script_file, args) + + print("Running CQR command...") + captured_output = run_create_resources(startup_script_file, args) + if captured_output.returncode != 0: + print(f"\n\nCreate resource request returned with ERROR returncode {captured_output.returncode}.\n") + print("Create resource error:\n" + captured_output.stderr.decode()) + return 1 + print("CQR command received! TPUs are being created.\n") + + #### Step 3: Cleanup #### + # Cleanup locally created directory + shutil.rmtree(tmp_dir) + # We leave the zipped script dir and log in GCS + + print("------------------------------------ \n") + print("multihost_job finished running, TPUs are firing up now to run your job remotely.\n") + + print(f"Your job is being logged, follow it here:\n{google_cloud_logging_url(args.RUN_NAME, args.PROJECT)}\n") + + print(f"To see the output of a single host, you may edit the slice and worker number in the log_file_path property here:"\ + f"\n{google_cloud_logging_single_host_url(args.RUN_NAME, args.PROJECT)}\n") + + print(f"When your job is finished, the main command log is in the GCS bucket here:"\ + f"\n{gcs_bucket_url(args.BUCKET_NAME, bucket_dir, args.PROJECT)}\n") + + print("View the status of the created TPUs via: ") + print(f"gcloud alpha compute tpus queued-resources list "\ + f"--filter={args.RUN_NAME} --zone={args.ZONE} --project={args.PROJECT}\n") + return 0 + +if __name__ == '__main__': + print("Name is __main__") + main() diff --git a/maxtext-setup/maxtext/multihost_runner.py b/maxtext-setup/maxtext/multihost_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..31d69ef639390257ce5988336a8ff45dfecdaa88 --- /dev/null +++ b/maxtext-setup/maxtext/multihost_runner.py @@ -0,0 +1,396 @@ +""" + Copyright 2023 Google LLC + + 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. + """ + +# pylint: disable=consider-using-with +""" Script to run a command in a multislice/multihost environment + +The "runner" host (the one which runs this script) and the "worker" hosts (the TPUS found by --TPU_PREFIX and +where the --COMMAND is run) should be different. You can use either a TPUVM or a non-TPUVM runner host, +but in the former case this host needs to be in the same project as the worker hosts, but not be one of the workers. + +Example usages: + Assuming runner.sh lives in directory path/to/dir: + python3 multihost_runner.py --TPU_PREFIX=mytpu-name --COMMAND="bash runner.sh" --SCRIPT_DIR=path/to/dir + This will recursively copy all of the files in path/to/dir to each tpu and run runner.sh + +Common issues: + Make sure your gcloud zone in set with e.g. + gcloud config set compute/zone us-central2-b + gcloud config set project + before running this script. + + You may have to create/authorize ssh-keys when first sshing into the TPUs. + For this purpose you may need to first run: + ssh-keygen -f ~/.ssh/google_compute_engine +""" + +import argparse +import sys +from collections import namedtuple +import subprocess +import time +from datetime import datetime +import os +import re + +##### Define flags ##### +def get_project(): + completed_command = subprocess.run(["gcloud", "config", "get", "project"], check=True, capture_output=True) + project_outputs = completed_command.stdout.decode().strip().split('\n') + if len(project_outputs) < 1 or project_outputs[-1]=='': + sys.exit("You must specify the project in the PROJECT flag or set it with 'gcloud config set project '") + return project_outputs[-1] # The project name lives on the last line of the output + +def get_zone(): + completed_command = subprocess.run(["gcloud", "config", "get", "compute/zone"], check=True, capture_output=True) + zone_outputs = completed_command.stdout.decode().strip().split('\n') + if len(zone_outputs) < 1 or zone_outputs[-1]=='': + sys.exit("You must specify the zone in the ZONE flag or set it with 'gcloud config set compute/zone '") + return zone_outputs[-1] # The zone name lives on the last line of the output + +def default_run_name(): + now = datetime.now() + return now.strftime("%Y-%m-%d-%H-%M-%S") + +parser = argparse.ArgumentParser(description='TPU configuration options') +parser.add_argument('--TPU_PREFIX', type=str, default=None, required=True, + help="Prefix of worker TPU's. E.g. if TPU's are named user-0 and user-1, \ + TPU_PREFIX should be set as user") +parser.add_argument('--PROJECT', type=str, default=None, + help='GCE project name, defaults to gcloud config project') +parser.add_argument('--ZONE', type=str, default=None, + help='GCE zone, e.g. us-central2-b, defaults to gcloud config compute/zone') +parser.add_argument('--SCRIPT_DIR', type=str, default=os.getcwd(), + help="The local location of the directory to copy to the TPUs and run the main command from. \ + Defaults to current working directory.") +parser.add_argument('--COMMAND', type=str, default=None, required=True, + help="Main command to run on each TPU. \ + This command is run from a copied version of SCRIPT_DIR on each TPU worker.") +parser.add_argument('--RUN_NAME', type=str, default=default_run_name(), + help="Name for the code directory on the TPU") +parser.add_argument('--USE_EXISTING_FOLDER', type=str, default="False", + help='If true, use the existing code directory on the TPU') +parser.add_argument('--INTERNAL_IP', type=str, default="False", + help="Set true if running script locally from a TPU or GCE instance, false otherwise.") +args = parser.parse_args() +args.USE_EXISTING_FOLDER = args.USE_EXISTING_FOLDER.lower() == "true" +args.INTERNAL_IP = args.INTERNAL_IP.lower() == "true" + +if not args.TPU_PREFIX: + raise ValueError("--TPU_PREFIX must be a non-empty string specifying your TPU slice names.") + +if args.USE_EXISTING_FOLDER is True and not args.RUN_NAME: + raise ValueError("When USE_EXISTING_FOLDER is true, RUN_NAME must be specified.") + +Slice = namedtuple('Slice', ['name', 'slice_num', 'num_workers', 'version']) + +def get_slices(): + """ Returns a list of slices matching TPU_PREFIX """ + command = [ + "gcloud", "alpha", "compute", "tpus", "tpu-vm", "list", + f"--filter=name~{args.TPU_PREFIX}", "--format=csv(name,accelerator_type)", + f"--project={args.PROJECT}", f"--zone={args.ZONE}" + ] + try: + completed_command = subprocess.run(command, capture_output=True, check=True) + except subprocess.CalledProcessError as e: + print(f"Error occurred trying to find TPU slices named {args.TPU_PREFIX} or matching regex \n {args.TPU_PREFIX}-[0-9]+ " + f"in project {args.PROJECT} zone {args.ZONE}") + print(f"Error is:\n {e.stderr}") + return [] + instances = completed_command.stdout.decode() + instance_list = instances.strip().split('\n') + instance_list = filter_instances(instance_list[1:], args.TPU_PREFIX) # First row is headers + num_slices = len(instance_list) + slices = [None for _ in range(num_slices)] + + if num_slices > 0: + print(f"{num_slices} slices found.", flush=True) + else: + print(f"No TPUs found with name {args.TPU_PREFIX} or matching regex {args.TPU_PREFIX}-[0-9]+ " + "in project {args.PROJECT} and zone {args.ZONE}.") + return [] + + slice_names = [instance.split(',')[0] for instance in instance_list] + slice_versions = [instance.split(',')[1] for instance in instance_list] + # Get number of workers in any slice (assume same worker count for all slices.) + command = [ + "gcloud", "compute", "tpus", "describe", slice_names[0], + "--flatten=networkEndpoints[]", "--format=csv[no-heading](networkEndpoints.ipAddress)", + f"--project={args.PROJECT}", f"--zone={args.ZONE}" + ] + completed_command = subprocess.run(command, capture_output=True, check=True) + num_workers = len(completed_command.stdout.decode().strip().split('\n')) + + for slice_name, version in zip(slice_names, slice_versions): + if num_slices > 1: + slice_num = int(slice_name.split('-')[-1]) + else: + slice_num = 0 + slices[slice_num] = Slice(slice_name, slice_num, num_workers, version) + return slices + +def filter_instances(instance_list, tpu_prefix): + # First look for exact match with tpu_prefix + for instance in instance_list: + if instance.split(',')[0] == tpu_prefix: + return [instance] + + # If no exact match, reg-exp full match "-[0-9]+" + re_pattern = tpu_prefix + "-[0-9]+" + return [instance for instance in instance_list if re.fullmatch(re_pattern, instance.split(',')[0])] + +def write_kill_script(kill_processes_script_name): + kill_processes_script = os.path.join(args.SCRIPT_DIR, kill_processes_script_name) + with open(kill_processes_script, "w", encoding="utf-8") as f: + f.write(kill_existing_processes_str()) + +def kill_existing_processes_str(): + return """#!/bin/bash +_TPU_VERSION_NAME="${1}" +device_name="accel" +if [[ "${_TPU_VERSION_NAME}" =~ ^v5.* ]]; then + device_name="vfio/" +fi +echo "Searching for existing processes on device ${device_name}..." +pids=$(sudo lsof -t /dev/${device_name}* | sort -u) +if [[ -n "${pids}" ]]; then + echo "Existing processes found with pid ${pids}" + for pid in ${pids}; do + echo "Killing process ${pid}..." + kill -9 "${pid}" + tail --pid="${pid}" -f /dev/null + echo "Existing process ${pid} on your TPU was killed successfully!" + done + echo "All existing processes killed, so your TPU is ready to use!" +else + echo "No existing processes found, so your TPU is ready to use!" +fi +sudo rm -f /tmp/libtpu_lockfile""" + +def scps(slices, run_name_dir, zip_name): + """ Zip the script directory, scp it to the TPUs, and unzip it there. """ + original_working_directory = os.getcwd() + os.chdir(args.SCRIPT_DIR) # To tar script_dir, it is most convenient to cd there. + + # Zip script directory + # Save the zip both to the logging directory, and the script directory. + # It will be removed from the script directory after the transfer to the TPUs + os.makedirs(run_name_dir, exist_ok=True) + zip_path = os.path.join(run_name_dir, zip_name) + command = ["tar","--exclude=tmp", "-czf", zip_path, "./"] + subprocess.run(command, check=True) + + # Move zip file to each tpuvm worker + commands = [] + worker_list = [] + for cur_slice in slices: + for worker_num in range(cur_slice.num_workers): + command = [ + "gcloud", "compute", "tpus", "tpu-vm", "scp", f"--worker={worker_num}", zip_path, + f"{cur_slice.name}:~/", "--strict-host-key-checking=no", f"--project={args.PROJECT}", f"--zone={args.ZONE}" + ] + if args.INTERNAL_IP: + command.append("--internal-ip") + commands.append(command) + worker_list.append([cur_slice.slice_num, worker_num]) + return_code, _ = run_commands(commands, 0, "SCP", worker_list) + if return_code != 0: + print("Failed to scp zipped code directory with error code ", return_code) + return return_code + + # Cleanup + os.chdir(original_working_directory) + + return return_code + +def execute_main_command(main_command, slices, local_log_dir, zip_name): + """ Run the main command on each worker, logging each separately. """ + kill_script_name = "kill_existing_processes.sh" # File written on worker machines + commands = [] + output_logs = [] + worker_list = [] + os.makedirs(local_log_dir, exist_ok=True) + + for slice_num, cur_slice in enumerate(slices): + for worker_num in range(cur_slice.num_workers): + output_filename = os.path.join(local_log_dir, f"output_slice_{cur_slice.slice_num:04d}_worker_{worker_num:04d}.txt") + output_logs.append(output_filename) + mkdir_command = f"mkdir -p {args.RUN_NAME}" + mv_zip_command = f"mv {zip_name} {args.RUN_NAME}" + cd_command = f"cd {args.RUN_NAME}" + unzip_command = f"tar xzf {zip_name}" + write_kill_script_command = f"echo '{kill_existing_processes_str()}' > {kill_script_name}" + kill_existing_command = f"bash {kill_script_name} {cur_slice.version}" + + if args.USE_EXISTING_FOLDER is False: + remote_command_list = [mkdir_command , mv_zip_command , cd_command , unzip_command , + write_kill_script_command , kill_existing_command , main_command] + else: + remote_command_list = [cd_command, write_kill_script_command , kill_existing_command , main_command] + remote_command_list_str = " && ".join(remote_command_list) + gcloud_command=[ + "gcloud", "alpha", "compute", "tpus", "tpu-vm", "ssh", cur_slice.name, f"--worker={worker_num}", + "--command", remote_command_list_str, "--strict-host-key-checking=no", + f"--project={args.PROJECT}", f"--zone={args.ZONE}"] + if args.INTERNAL_IP: + gcloud_command.append("--internal-ip") + commands.append(gcloud_command) + worker_list.append([slice_num, worker_num]) + + return_code, return_codes = run_commands(commands, 0, "MAIN COMMAND", worker_list, output_logs=output_logs) + if return_code > 0: + failure_index = next((i for i, x in enumerate(return_codes) if x), None) + print(f"Main command failed on slice {worker_list[failure_index][0]} worker"\ + f" {worker_list[failure_index][1]} with error code {return_codes[failure_index]}, see logs for details", flush=True) + return return_code + +def run_commands(commands, id_to_print, jobname, worker_list, is_shell=False, output_logs=None, fail_fast=True): + ''' Runs commands in parallel. + Inputs: + commands: list of n commands, each command is a a list of strings + id_to_print: which command is printed to the terminal, typically 0 or None + jobname: Useful debugging name for the group of commands, such as SCP + worker_list: list of n pairs of (slice_id, worker_id) + is_shell: Boolean directly passed as shell argument to subprocess.Popen + output_logs: list of n log paths, each command will output to each log. + fail_fast: If true, when one command fails immediately terminate others + ''' + + children = [] + start_time = datetime.now() + for i, command in enumerate(commands): + if output_logs and i == id_to_print: + persistent_log = open(output_logs[i], "w", encoding="utf-8") + output_log = Tee(sys.stdout, persistent_log) + elif output_logs: + output_log = open(output_logs[i], "w", encoding="utf-8") + elif i == id_to_print: + output_log = None + else: + output_log = subprocess.DEVNULL + + children.append(subprocess.Popen(command, stdout=output_log, stderr=output_log, shell=is_shell)) + + while True: + returncodes = [child.poll() for child in children] + max_returncode = max([0]+[r for r in returncodes if r is not None]) + completed = len([r for r in returncodes if r is not None]) + total = len(returncodes) + seconds_elapsed = (datetime.now() - start_time).total_seconds() + if completed < total: + slow_worker_index = returncodes.index(None) + slow_worker = worker_list[slow_worker_index] + slow_str = f", slice {slow_worker[0]} worker {slow_worker[1]} still working" + else: + slow_str = "" + print(f"[t={seconds_elapsed:.2f}, {jobname}] Completed {completed}/{total}{slow_str}...") + + if seconds_elapsed >= 60 and not 0 in returncodes and jobname == "SCP": + print("SCP operation timed out - terminating all processes."\ + " Please check that --INTERNAL_IP flag is set correctly.") + for child in children: + child.terminate() + max_returncode = 255 + break + + if fail_fast and max_returncode > 0: + print(f"Terminating all {jobname} processes since at least one failed.") + for child in children: + child.terminate() + break + + if completed == total: + break + + time.sleep(1) + return max_returncode, returncodes + +def assert_script_dir_exists(script_dir): + if not os.path.isdir(script_dir): + sys.exit(f"No directory named {script_dir} found.") + +class Tee: + """ Helper class to print subprocess to both stdout and a log file. """ + def __init__(self, *files, bufsize=1): + files = [x.fileno() if hasattr(x, 'fileno') else x for x in files] + read_fd, write_fd = os.pipe() + pid = os.fork() + if pid: + os.close(read_fd) + self._fileno = write_fd + self.child_pid = pid + return + os.close(write_fd) + while buf := os.read(read_fd, bufsize): + for f in files: + os.write(f, buf) + os._exit(0) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def fileno(self): + return self._fileno + + def close(self): + os.close(self._fileno) + os.waitpid(self.child_pid, 0) + +################### Main ################### +def main() -> None: + print("Starting multihost runner...", flush=True) + + ##### Validate arguments ##### + if not args.PROJECT: + args.PROJECT = get_project() + if not args.ZONE: + args.ZONE = get_zone() + + assert_script_dir_exists(args.SCRIPT_DIR) + + ##### Step 1: Get the workers ##### + slices = get_slices() + if not slices: + print(f"Failed to retrieve slices {args.TPU_PREFIX} in project {args.PROJECT} zone {args.ZONE}", flush=True) + return 1 + + local_log_dir = os.path.join("/tmp", args.RUN_NAME, "") + zip_name = "script_dir_zip_" + args.RUN_NAME + ".tar.gz" + + if args.USE_EXISTING_FOLDER is False: + ##### Step 2 when using a new folder: Zip code and move it to the TPUs ##### + return_code = scps(slices, local_log_dir, zip_name) + if return_code > 0: + print(f"Moving the directory {args.SCRIPT_DIR} to the VMs failed with error code {return_code}") + return return_code + + ##### Step 3: Unzip if using a new folder, kill existing processes, and run ##### + print(f"Running main command, logs located in: {local_log_dir}", flush=True) + return_code = execute_main_command(args.COMMAND, slices, local_log_dir, zip_name) + if return_code == 0: + print(f"Main command completed successfully, logs located in: {local_log_dir}", flush=True) + print("Multihost runner finished successfully!", flush=True) + return 0 + else: + print(f"Main command finished with errors, check the logs located in: {local_log_dir}", flush=True) + return return_code + +if __name__ == '__main__': + main() diff --git a/maxtext-setup/maxtext/pedagogical_examples/non_spmd.py b/maxtext-setup/maxtext/pedagogical_examples/non_spmd.py new file mode 100644 index 0000000000000000000000000000000000000000..743bd4138453fa82dc0586d08ed444ad923c0130 --- /dev/null +++ b/maxtext-setup/maxtext/pedagogical_examples/non_spmd.py @@ -0,0 +1,56 @@ +#!/usr/bin/python3 + +""" + Copyright 2023 Google LLC + + 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. + """ + +''' +This programs demonstrates embarrassingly parallelizable non-SPMD computations in Jax, in this case by having each +process_index run its own computation. +The same approach can be extended for non-embarrassingly parallelizable computations. +The simplest way to do that would be by running embarrassingly parallelizable computations on arbitrary submeshes, +then using a `host_local_array_to_global_array` to reshard into a new global array. +An important limitation of this approach is that we cannot overlap communication and computation between the different +kernel calls. +''' + + +import jax +from jax.sharding import PartitionSpec +from jax.sharding import Mesh + +import numpy as np + + + + +# Notice this is jax.local_devices(), not jax.devices(). Hence each process (on TPUVMs, each VM) will run separate programs +# on its mesh. +mesh = Mesh(np.array(jax.local_devices()), ["data"]) +sharding = jax.sharding.NamedSharding(mesh, PartitionSpec(None)) +idx = jax.process_index() + +# Example step depends on idx which is different on each program +def example_step(): + return idx * jax.numpy.ones((idx+1)) + +jit_func = jax.jit( + example_step, + out_shardings=sharding, + ) + +print(f"{idx=} -> {jit_func()=}") + + diff --git a/maxtext-setup/maxtext/pedagogical_examples/shardings.py b/maxtext-setup/maxtext/pedagogical_examples/shardings.py new file mode 100644 index 0000000000000000000000000000000000000000..85198c3ee9d74592cae884224bcf39018247f144 --- /dev/null +++ b/maxtext-setup/maxtext/pedagogical_examples/shardings.py @@ -0,0 +1,274 @@ +#!/usr/bin/python3 + +""" + Copyright 2023 Google LLC + + 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. + """ + +'''This script is used to measure the performance of different sharding schemes on TPU.''' + +from absl import app +from absl import flags +import jax +from jax.sharding import PartitionSpec +from jax.sharding import Mesh +from jax.experimental import mesh_utils +from jax._src.pjit import with_sharding_constraint + +import argparse +import datetime +import numpy as np +from typing import Sequence + +parser = argparse.ArgumentParser( + description="Experiment different sharding techniques with a simple NN.\ + Ensure 1) The product of dcn dimensions == number of slices \ + 2) product of ici dimension = number of devices per slice" + ) +parser.add_argument( + "--profiler_path", "-p", + required=False, + default="", + help="Path to the profiler where the script will write to.", + type=str +) +parser.add_argument( + "--embedding_dimension", "-d", + required=False, + default=2048, + type=int +) +parser.add_argument( + "--batch_size", "-b", + required=False, + default=131072, + type=int +) +parser.add_argument( + "--num_layers", "-n", + required=False, + default=4, + type=int +) +parser.add_argument( + "--dcn_data_parallelism", "-dd", + help="N-way Data Parallelism across slices", + required=False, + default=1, + type=int +) +parser.add_argument( + "--dcn_fsdp_parallelism", "-df", + help="Fsdp parallelism across slices that is expected to be 1 in most cases", + required=False, + default=1, + type=int +) +parser.add_argument( + "--dcn_tensor_parallelism", "-dt", + help="Tensor parallelism across slices that is expected to be 1 in most cases", + required=False, + default=1, + type=int +) +parser.add_argument( + "--ici_data_parallelism", "-id", + help="Data parallelism within each slice that is expected to be 1 in most cases", + required=False, + default=1, + type=int +) +parser.add_argument( + "--ici_fsdp_parallelism", "-if", + help="Number of shards for Fsdp Parallelism within each slice.", + required=False, + default=4, + type=int +) +parser.add_argument( + "--ici_tensor_parallelism", "-it", + help="Number of shards for Tensor Parallelism within each slice.", + required=False, + default=1, + type=int +) +args = parser.parse_args() + +def main(_argv: Sequence[str]) -> None: + def activate_profiler(profiler_path): + if profiler_path: + print(f"profiling to {profiler_path}") + jax.profiler.start_trace(profiler_path) + + def deactivate_profiler(profiler_path): + if profiler_path: + jax.profiler.stop_trace() + + def simple_timeit(f, tries = 5, verbose = True): + '''Simple utility to time a function for multiple runs''' + outcomes = [] + f() #warm it up! + for _ in range(tries): + s = datetime.datetime.now() + f() + e = datetime.datetime.now() + outcomes.append((e-s).total_seconds()) + average_time = sum(outcomes)/len(outcomes) + if verbose: + print(f"average time: {average_time}, timings (seconds) {outcomes}") + return average_time + + dcn_parallelism = [args.dcn_data_parallelism, args.dcn_fsdp_parallelism, args.dcn_tensor_parallelism] + ici_parallelism = [args.ici_data_parallelism, args.ici_fsdp_parallelism, args.ici_tensor_parallelism] + + devices = jax.devices() + num_devices = len(devices) + print(f"Devices: {devices} (num_devices: {num_devices})") + assert len(devices) > 1, "You must have at least two devices" + + # Assert that we have correct inputs of sharding that fit the number of chips + assert np.product(dcn_parallelism) * np.product(ici_parallelism) == num_devices, f"Number of devices {num_devices} \ + does not match the product of the parallelism {np.product(dcn_parallelism) * np.product(ici_parallelism)}" + + multi_slice_env = hasattr(jax.devices()[0], 'slice_index') + # Create device mesh + + if multi_slice_env: + assert args.dcn_data_parallelism == 1 + max(x.slice_index for x in jax.devices()), \ + f"Number of slices given {args.dcn_data_parallelism} \ + does not match the number fetched from jax devices {jax.devices()[0]}" + devices_array = mesh_utils.create_hybrid_device_mesh(ici_parallelism, dcn_parallelism) + else: + devices_array = mesh_utils.create_device_mesh(ici_parallelism) + + print(f"Decided on mesh shape: {devices_array}") + + mesh = Mesh(devices_array, ["data", "fsdp", "tensor"]) + + data_sharding = PartitionSpec(("data", "fsdp"), "tensor") + # We assume parameters are stored in a decreasing order of dimension size + parameter_sharding = PartitionSpec("tensor", "fsdp") + + BATCH = len(jax.devices()) * args.batch_size + D_EMB = args.embedding_dimension + D_FF = 4 * D_EMB + NUM_LAYERS = args.num_layers + + parameters = 2 * D_FF * D_EMB * NUM_LAYERS + parameter_bytes = 2 * parameters + activation_bytes = 2 * ( BATCH * ( D_FF+D_EMB) ) * NUM_LAYERS + memory_bytes = parameter_bytes + activation_bytes + + print(f"total {memory_bytes/1e9} GB, parameters {parameter_bytes/1e9} GB, activations {activation_bytes/1e9} GB") + + def gen_layer(random_key): + keys = jax.random.split(random_key, num = 4) + return { + "EMB2FF" : 1e-4 * jax.random.normal( keys[0], (D_FF, D_EMB), dtype=jax.numpy.bfloat16), + "FF2EMB" : 1e-4 * jax.random.normal( keys[1], (D_FF, D_EMB), dtype=jax.numpy.bfloat16), + } + + def gen_layers(random_key): + layers = [] + for _ in range(NUM_LAYERS): + random_key, sub_key = jax.random.split(random_key) + layers.append(gen_layer(sub_key)) + return tuple(layers) + + def gen_data(random_key): + return jax.random.uniform(random_key, (BATCH, D_EMB), dtype=jax.numpy.bfloat16 ) + + + def multiply_layer(in_act, in_layer): + with jax.named_scope("M1"): + M1 = jax.nn.sigmoid(in_act @ in_layer["EMB2FF"].T) + M1 = with_sharding_constraint(M1, data_sharding) + with jax.named_scope("M2"): + M2 = jax.nn.sigmoid(M1 @ in_layer["FF2EMB"]) + M2 = with_sharding_constraint(M2, data_sharding) + + return M2 + + def multiply_layers(in_act, in_layers): + x = in_act + + for i, layer in enumerate(in_layers): + with jax.named_scope(f"layer_{i}"): + x = with_sharding_constraint(multiply_layer(x, layer), data_sharding) + + return x, in_layers + + def multiply_layers_with_loss(in_act, in_layers): + x, _ = multiply_layers(in_act, in_layers) + return jax.numpy.sum(x) + + multiply_layers_and_grad = jax.value_and_grad(multiply_layers_with_loss, argnums=[1]) + + def training_step(in_act, in_layers): + _, grad_layers = multiply_layers_and_grad(in_act, in_layers) + out_layers = jax.tree_map(lambda param, grad: param - 1e-4 * grad, in_layers, grad_layers[0]) + return out_layers + + print("finished includes ", flush = True) + + replicated_sharding = jax.sharding.NamedSharding(mesh, data_sharding) + + parameter_mesh_shardings = jax.tree_map( + lambda p: jax.sharding.NamedSharding(mesh, p), parameter_sharding) + + data_pspec_shardings = jax.tree_map( + lambda p: jax.sharding.NamedSharding(mesh, p), parameter_sharding) + + jit_func = jax.jit( + training_step, + in_shardings=(replicated_sharding, parameter_mesh_shardings), + out_shardings=data_pspec_shardings, + ) + + data_mesh_shardings = jax.tree_map( + lambda p: jax.sharding.NamedSharding(mesh, p), data_sharding) + + jit_gen_data = jax.jit( + gen_data, + in_shardings=None, + out_shardings=data_mesh_shardings + ) + + parameter_mesh_shardings = jax.tree_map( + lambda p: jax.sharding.NamedSharding(mesh, p), parameter_sharding) + + jit_gen_layers = jax.jit( + gen_layers, + in_shardings=None, + out_shardings=parameter_mesh_shardings + ) + + # starting the profiler outside `with` statement, + # will call it right before the computation once b/301309635 is resolved + activate_profiler(args.profiler_path) + with Mesh(mesh.devices, mesh.axis_names): + key = jax.random.PRNGKey(0) + presharded_X = jax.block_until_ready(jit_gen_data(key)) + presharded_layers = jax.block_until_ready(jit_gen_layers(key)) + TFLOPs_per_device = parameters * 6 * BATCH / 10**12 / len(jax.devices()) + time = simple_timeit(lambda : jax.block_until_ready(jit_func(presharded_X, presharded_layers))) + print(f"time is {time} seconds, TFLOP is {TFLOPs_per_device}, TFLOP/s is {TFLOPs_per_device/time}", flush = True) + deactivate_profiler(args.profiler_path) + +def parse_flags(argv): + return parser.parse_args(argv[1:]) + +if __name__ == "__main__": + flags.FLAGS.mark_as_parsed() + app.run(main, flags_parser=parse_flags) diff --git a/maxtext-setup/maxtext/pedagogical_examples/shmap_collective_matmul.py b/maxtext-setup/maxtext/pedagogical_examples/shmap_collective_matmul.py new file mode 100644 index 0000000000000000000000000000000000000000..fe8c38be9b049043efedeb874b4cf6483c5296dc --- /dev/null +++ b/maxtext-setup/maxtext/pedagogical_examples/shmap_collective_matmul.py @@ -0,0 +1,209 @@ +#!/usr/bin/python3 + +""" + Copyright 2023 Google LLC + + 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. + """ + +'''This script is an example collective matmul.''' + +import os +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "0" + +import numpy as np +from functools import partial +import jax +import jax.numpy as jnp +from jax.experimental.pjit import pjit +from jax.sharding import PartitionSpec as P +from jax.experimental import mesh_utils +from jax.sharding import Mesh +from jax.experimental.shard_map import shard_map + +MESH_DATA_AXIS = "dp" +MESH_FSDP_AXIS = "fsdp" +MESH_TENSOR_AXIS = "tp" + +d = jax.devices() +outd = [[[d[0], d[1], d[3], d[2]]]] +global_mesh = Mesh(outd, (MESH_DATA_AXIS, MESH_FSDP_AXIS, MESH_TENSOR_AXIS)) +print(global_mesh.shape) + +batch_size = 2 +seq_len = 8192 +n_heads = 128 +head_dim = 128 +emb_dim = 16384 + +import random +import string +import datetime + +def simple_timeit(f, *args, tries = 10, trace_base_dir = None, task = None): + '''Simple utility to time a function for multiple runs''' + assert task is not None + + trace_name = f"t_{task}_" + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) + + if trace_base_dir: + trace_dir = f"{trace_base_dir}/{trace_name}" + else: + trace_dir = None + + outcomes_ms = [] + jax.block_until_ready(f(*args)) #warm it up! + if trace_dir: + jax.profiler.start_trace(trace_dir) + + for _ in range(tries): + s = datetime.datetime.now() + jax.block_until_ready(f(*args)) + e = datetime.datetime.now() + outcomes_ms.append(1000*(e-s).total_seconds()) + if trace_dir: + jax.profiler.stop_trace() + + average_time_ms = sum(outcomes_ms)/len(outcomes_ms) + print(f"{task}: average time milliseconds: {average_time_ms:.2f}") + return average_time_ms + +# gen data +def gen_data_fn(): + key = jax.random.PRNGKey(np.random.randint(0, 256)) + activations = jax.random.normal(key, shape=(batch_size, seq_len, emb_dim), dtype=jnp.bfloat16) + weights = jax.random.normal(key, shape=(emb_dim, n_heads, head_dim), dtype=jnp.bfloat16) + return activations, weights + +data_fn = pjit( + gen_data_fn, + out_shardings=(P(MESH_FSDP_AXIS, MESH_TENSOR_AXIS, None), P(MESH_FSDP_AXIS, MESH_TENSOR_AXIS, None)), +) + +def matmul(activations, weights): + return jnp.einsum("bsE,Ehd->bshd", activations, weights) + +jit_matmul = pjit(matmul, out_shardings=P(MESH_FSDP_AXIS, None, MESH_TENSOR_AXIS, None)) + +@partial( + shard_map, + mesh=global_mesh, + in_specs=( + P(MESH_FSDP_AXIS, MESH_TENSOR_AXIS, None), + P(MESH_FSDP_AXIS, MESH_TENSOR_AXIS, None), + ), + out_specs=P(MESH_FSDP_AXIS, None, MESH_TENSOR_AXIS, None), + check_rep=False, +) +def collective_matmul(activations, weights): + print(f"sh_map {activations.shape=} {weights.shape=}") + + axis_size = jax.lax.psum(1, axis_name=MESH_TENSOR_AXIS) + axis_index = jax.lax.axis_index(axis_name=MESH_TENSOR_AXIS) + # The current sequence chunk + chunk_size = activations.shape[1] + mid_chunk = chunk_size // 2 + # create accum buffer + accum = jnp.zeros( + ( + activations.shape[0], + activations.shape[1] * axis_size, + weights.shape[-2], + weights.shape[-1], + ), + dtype=activations.dtype, + ) + + # compute first chunk + update = jnp.einsum("bsE,Ehd->bshd", activations, weights) + update_index = (0, axis_index * chunk_size, 0, 0) + accum = jax.lax.dynamic_update_slice(accum, update, update_index) + activation_forward, activation_backward = jnp.split(activations, 2, axis=1) + activation_forward = jax.lax.ppermute( + activation_forward, + axis_name=MESH_TENSOR_AXIS, + perm=[(j, (j + 1) % axis_size) for j in range(axis_size)], + ) + activation_backward = jax.lax.ppermute( + activation_backward, + axis_name=MESH_TENSOR_AXIS, + perm=[(j, (j - 1) % axis_size) for j in range(axis_size)], + ) + + # split activations into chunks and send + def scanned_call(i, carrys): + accum, activation_forward, activation_backward = carrys + update_forward = jnp.einsum("bsE,Ehd->bshd", activation_forward, weights) + update_backward = jnp.einsum("bsE,Ehd->bshd", activation_backward, weights) + + activation_forward = jax.lax.ppermute( + activation_forward, + axis_name=MESH_TENSOR_AXIS, + perm=[(j, (j + 1) % axis_size) for j in range(axis_size)], + ) + activation_backward = jax.lax.ppermute( + activation_backward, + axis_name=MESH_TENSOR_AXIS, + perm=[(j, (j - 1) % axis_size) for j in range(axis_size)], + ) + + forward_update_index = ((axis_index - i - 1) % axis_size) * chunk_size + backward_update_index = ((axis_index + i + 1) % axis_size) * chunk_size + mid_chunk + + accum = jax.lax.dynamic_update_slice(accum, update_forward, (0, forward_update_index, 0, 0)) + accum = jax.lax.dynamic_update_slice(accum, update_backward, (0, backward_update_index, 0, 0)) + return (accum, activation_forward, activation_backward) + + print(f"{accum.shape=}") + + accum, _, _ = jax.lax.fori_loop( + 0, (axis_size - 1), scanned_call, (accum, activation_forward, activation_backward) + ) + return accum + +with global_mesh: + activations, weights = data_fn() + + jax.block_until_ready(activations) + jax.block_until_ready(weights) + + @jax.jit + def run_naive(_activations, _weights): + with jax.named_scope("naive_matmul"): + outputs = jit_matmul(_activations, _weights) + return outputs + + @jax.jit + def run_collective(_activations, _weights): + with jax.named_scope("collective_matmul"): + manual_outputs = jax.jit(collective_matmul)(_activations, _weights) + return manual_outputs + + + + + naive_outputs = run_naive(activations, weights) + collective_outputs = run_collective(activations, weights) + + print(f"input {activations.shape=} {activations.addressable_shards[0].data.shape=}") + print(f"input {weights.shape=} {weights.addressable_shards[0].data.shape=}") + print(f"naive_outputs {naive_outputs.shape=} {naive_outputs.addressable_shards[0].data.shape=}") + print(f"collective_outputs {collective_outputs.shape=} {collective_outputs.addressable_shards[0].data.shape=}") + + + + assert jnp.allclose(naive_outputs, collective_outputs), "Two algorithms should match but don't" + + simple_timeit(run_naive, activations, weights, task = "naive") + simple_timeit(run_collective, activations, weights, task = "collective") + diff --git a/maxtext-setup/maxtext/preflight.sh b/maxtext-setup/maxtext/preflight.sh new file mode 100644 index 0000000000000000000000000000000000000000..032a0c2a628c2d87b40a7bba24617e53f435caef --- /dev/null +++ b/maxtext-setup/maxtext/preflight.sh @@ -0,0 +1,40 @@ +#!/bin/bash +echo "Running preflight.sh" +# Command Flags: +# PLATFORM (Required, must be "gke" or "gce") +# +# Example to invoke this script: +# bash preflight.sh PLATFORM=[GCE or GKE] + +# Warning: +# For any dependencies, please add them into `setup.sh` or `maxtext_dependencies.Dockerfile`. +# You should not install any dependencies in this file. + +# Stop execution if any command exits with error +set -e + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +if [ -z $PLATFORM ]; then + echo "Error: PLATFORM flag is missing." + exit 1 +fi + +# Check if sudo is available +if command -v sudo >/dev/null 2>&1; then + # sudo is available, use it + echo "running rto_setup.sh with sudo" + + # apply network settings. + sudo bash rto_setup.sh +else + # sudo is not available, run the script without sudo + echo "running rto_setup.sh without sudo" + + # apply network settings. + bash rto_setup.sh +fi \ No newline at end of file diff --git a/maxtext-setup/maxtext/pylintrc b/maxtext-setup/maxtext/pylintrc new file mode 100644 index 0000000000000000000000000000000000000000..4897238f0667c6ed0c03478fe21e7e9976771875 --- /dev/null +++ b/maxtext-setup/maxtext/pylintrc @@ -0,0 +1,412 @@ +# This Pylint rcfile contains a best-effort configuration to uphold the +# best-practices and style described in the Google Python style guide: +# https://google.github.io/styleguide/pyguide.html +# +# Its canonical open-source location is: +# https://google.github.io/styleguide/pylintrc + +[MASTER] + +# Add files or directories to the blocked list. They should be base names, not +# paths. +ignore=third_party + +# Add files or directories matching the regex patterns to the blocked list. The +# regex matches against base names, not paths. +ignore-patterns= + +# Pickle collected data for later comparisons. +persistent=no + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Use multiple processes to speed up Pylint. +jobs=4 + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED +confidence= + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +#enable= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once).You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use"--disable=all --enable=classes +# --disable=W" +disable=apply-builtin, + backtick, + bad-option-value, + buffer-builtin, + c-extension-no-member, + cmp-builtin, + cmp-method, + coerce-builtin, + coerce-method, + delslice-method, + div-method, + duplicate-code, + eq-without-hash, + execfile-builtin, + file-builtin, + filter-builtin-not-iterating, + fixme, + getslice-method, + global-statement, + hex-method, + idiv-method, + implicit-str-concat-in-sequence, + import-error, + import-self, + import-star-module-level, + input-builtin, + intern-builtin, + invalid-str-codec, + locally-disabled, + long-builtin, + long-suffix, + map-builtin-not-iterating, + metaclass-assignment, + next-method-called, + next-method-defined, + no-absolute-import, + no-else-break, + no-else-continue, + no-else-raise, + no-else-return, + no-member, + no-self-use, + nonzero-method, + oct-method, + old-division, + old-ne-operator, + old-octal-literal, + old-raise-syntax, + parameter-unpacking, + pointless-string-statement, + print-statement, + raising-string, + range-builtin-not-iterating, + raw_input-builtin, + rdiv-method, + reduce-builtin, + relative-import, + reload-builtin, + round-builtin, + setslice-method, + signature-differs, + standarderror-builtin, + suppressed-message, + sys-max-int, + too-few-public-methods, + too-many-ancestors, + too-many-arguments, + too-many-boolean-expressions, + too-many-branches, + too-many-instance-attributes, + too-many-locals, + too-many-public-methods, + too-many-return-statements, + too-many-statements, + trailing-newlines, + unichr-builtin, + unicode-builtin, + unpacking-in-except, + useless-else-on-loop, + useless-suppression, + using-cmp-argument, + wrong-import-order, + wrong-import-position, + xrange-builtin, + zip-builtin-not-iterating, + invalid-name, + +[REPORTS] + +# Set the output format. Available formats are text, parseable, colorized, msvs +# (visual studio) and html. You can also give a reporter class, eg +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages +reports=no + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details +#msg-template= + + +[BASIC] + +# Good variable names which should always be accepted, separated by a comma +good-names=main,_ + +# Bad variable names which should always be refused, separated by a comma +bad-names= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Include a hint for the correct naming format with invalid-name +include-naming-hint=no + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +property-classes=abc.abstractproperty,cached_property.cached_property,cached_property.threaded_cached_property,cached_property.cached_property_with_ttl,cached_property.threaded_cached_property_with_ttl + +# Regular expression matching correct function names +function-rgx=^(?:(?PsetUp|tearDown|setUpModule|tearDownModule)|(?P_?[A-Z][a-zA-Z0-9]*)|(?P_?[a-z][a-z0-9_]*))$ + +# Regular expression matching correct variable names +variable-rgx=^[a-z][a-z0-9_]*$ + +# Regular expression matching correct constant names +const-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ + +# Regular expression matching correct attribute names +attr-rgx=^_{0,2}[a-z][a-z0-9_]*$ + +# Regular expression matching correct argument names +argument-rgx=^[a-z][a-z0-9_]*$ + +# Regular expression matching correct class attribute names +class-attribute-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ + +# Regular expression matching correct inline iteration names +inlinevar-rgx=^[a-z][a-z0-9_]*$ + +# Regular expression matching correct class names +class-rgx=^_?[A-Z][a-zA-Z0-9]*$ + +# Regular expression matching correct module names +module-rgx=^(_?[a-z][a-z0-9_]*|__init__)$ + +# Regular expression matching correct method names +method-rgx=(?x)^(?:(?P_[a-z0-9_]+__|runTest|setUp|tearDown|setUpTestCase|tearDownTestCase|setupSelf|tearDownClass|setUpClass|(test|assert)_*[A-Z0-9][a-zA-Z0-9_]*|next)|(?P_{0,2}[A-Z][a-zA-Z0-9_]*)|(?P_{0,2}[a-z][a-z0-9_]*))$ + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=(__.*__|main|test.*|.*test|.*Test)$ + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=10 + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager,contextlib2.contextmanager + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + + +[FORMAT] + +# Maximum number of characters on a single line. +max-line-length=125 + +# TODO(https://github.com/PyCQA/pylint/issues/3352): Direct pylint to exempt +# lines made too long by directives to pytype. + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=(?x)( + ^\s*(\#\ )??$| + ^\s*(from\s+\S+\s+)?import\s+.+$) + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=yes + +# Maximum number of lines in a module +max-module-lines=99999 + +# String used as indentation unit. The internal Google style guide mandates 2 +# spaces. Google's externaly-published style guide says 4, consistent with +# PEP 8. Here, we use 2 spaces, for conformity with many open-sourced Google +# projects (like TensorFlow). +indent-string=' ' + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=TODO + + +[VARIABLES] + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# A regular expression matching the name of dummy variables (i.e. expectedly +# not used). +dummy-variables-rgx=^\*{0,2}(_$|unused_|dummy_) + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_,_cb + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six,six.moves,past.builtins,future.builtins,functools + + +[LOGGING] + +# Logging modules to check that the string format arguments are in logging +# function parameter format +logging-modules=logging,absl.logging + + +[SIMILARITIES] + +# Minimum lines number of a similarity. +min-similarity-lines=4 + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + + +[SPELLING] + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[IMPORTS] + +# Deprecated modules which should not be used, separated by a comma +deprecated-modules=regsub, + TERMIOS, + Bastion, + rexec, + sets + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled) +import-graph= + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled) +ext-import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled) +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant, absl + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls, + class_ + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "Exception" +overgeneral-exceptions=builtins.StandardError, + builtins.Exception, + builtins.BaseException diff --git a/maxtext-setup/maxtext/requirements.txt b/maxtext-setup/maxtext/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b23fe6d5f1f8d38a5f959be926473789e4cd295f --- /dev/null +++ b/maxtext-setup/maxtext/requirements.txt @@ -0,0 +1,25 @@ +jax>=0.4.23 +jaxlib>=0.4.23 +orbax-checkpoint>=0.5.5 +absl-py +array-record +aqtp +cloud-tpu-diagnostics +google-cloud-storage +grain-nightly +flax>=0.8.0 +ml-collections +numpy +optax +protobuf==3.20.3 +pylint +pytest +pytype +sentencepiece==0.1.97 +tensorflow-text>=2.13.0 +tensorflow>=2.13.0 +tensorflow-datasets +tensorboardx +tensorboard-plugin-profile +git+https://github.com/mlperf/logging.git +google-jetstream diff --git a/maxtext-setup/maxtext/rto_setup.sh b/maxtext-setup/maxtext/rto_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..742a03f493c3d7f7cdf0b5830848f01346e49b13 --- /dev/null +++ b/maxtext-setup/maxtext/rto_setup.sh @@ -0,0 +1,61 @@ +echo "Running rto_setup.sh" + +# Stop execution if any command exits with error +set -e + +echo "Adjust Network settings and apply non cache copy" + +# Install ip. +apt-get update +yes | apt-get install net-tools +yes | apt-get install iproute2 +yes | apt-get install procps +yes | apt-get install ethtool + +# Disable slow start after idle +sysctl net.ipv4.tcp_slow_start_after_idle=0 + +# Disable metrics cache +sysctl net.ipv4.tcp_no_metrics_save=1 + +# Address rto_min issue with two default routing entries: screen/7RGgkiXkGXSeYF2 +route=$(ip route show | sed -n 1p) +second_route=$(ip route show | sed -n 2p) +if [[ "${second_route}" =~ ^default.* ]]; then + modified_route=${route//" lock"/} + ip route delete ${modified_route} +fi +route=$(ip route show | sed -n 1p) +echo "route rto before change: $route" +if [[ "${route}" =~ .*lock.*5ms.* ]]; then + echo "${route}" +else + # shellcheck disable=SC2086 + ip route change $route rto_min 5ms +fi +route=$(ip route show | sed -n 1p) +echo "route rto after change: $route" + +# Disable Cubic Hystart Ack-Train +echo 2 > /sys/module/tcp_cubic/parameters/hystart_detect + +# Improve handling SYN burst +echo 4096 > /proc/sys/net/core/somaxconn +echo 4096 > /proc/sys/net/ipv4/tcp_max_syn_backlog + +# Disable MTU Discovery +echo 0 > /proc/sys/net/ipv4/tcp_mtu_probing + +# Increase TCP Zerocopy control memory +sysctl -w net.core.optmem_max=131072 + +# Printing output of `ip route show` +echo -e "\nPrinting output of 'ip route show':" +ip route show + +first_line_res=$(ip route show | head -n 1) +dev_name=$(echo "$first_line_res" | awk -F'[[:space:]]' '{ print $5 }') +echo "dev_name=${dev_name}" +ethtool -K "${dev_name}" tx-nocache-copy on + +echo "rto_setup.sh finished" \ No newline at end of file diff --git a/maxtext-setup/maxtext/setup.sh b/maxtext-setup/maxtext/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..aa36a7ddff9ad183505814b035c5c7b468595e96 --- /dev/null +++ b/maxtext-setup/maxtext/setup.sh @@ -0,0 +1,175 @@ +#!/bin/bash + +# Copyright 2023 Google LLC +# +# 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. + +# Description: +# bash setup.sh MODE={stable,nightly,libtpu-only} LIBTPU_GCS_PATH={gcs_path_to_custom_libtpu} DEVICE={tpu,gpu} + + +# You need to specify a MODE, default value stable. +# You have the option to provide a LIBTPU_GCS_PATH that points to a libtpu.so provided to you by Google. +# In libtpu-only MODE, the LIBTPU_GCS_PATH is mandatory. +# For MODE=stable you may additionally specify JAX_VERSION, e.g. JAX_VERSION=0.4.13 + + +# Enable "exit immediately if any command fails" option +set -e +export DEBIAN_FRONTEND=noninteractive + +(sudo bash || bash) <<'EOF' +apt update && \ +apt install -y numactl && \ +apt install -y lsb-release && \ +apt install -y gnupg && \ +apt install -y curl +export GCSFUSE_REPO=gcsfuse-`lsb_release -c -s` +echo "deb https://packages.cloud.google.com/apt $GCSFUSE_REPO main" | tee /etc/apt/sources.list.d/gcsfuse.list +curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add - +apt update -y && apt -y install gcsfuse +rm -rf /var/lib/apt/lists/* +EOF + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" +done + +if [[ -z "$DEVICE" ]]; then + export DEVICE="tpu" +fi + +if [[ $JAX_VERSION == NONE ]]; then + unset JAX_VERSION +fi + +if [[ $LIBTPU_GCS_PATH == NONE ]]; then + unset LIBTPU_GCS_PATH +fi + +if [[ -n $JAX_VERSION && ! ($MODE == "stable" || -z $MODE) ]]; then + echo -e "\n\nError: You can only specify a JAX_VERSION with stable mode.\n\n" + exit 1 +fi + +if [[ $DEVICE == "tpu" ]]; then + libtpu_path="$HOME/custom_libtpu/libtpu.so" + if [[ "$MODE" == "libtpu-only" ]]; then + # Only update custom libtpu. + if [[ -n "$LIBTPU_GCS_PATH" ]]; then + # Install custom libtpu + echo "Installing libtpu.so from $LIBTPU_GCS_PATH to $libtpu_path" + # Install required dependency + pip3 install -U crcmod + # Copy libtpu.so from GCS path + gsutil cp "$LIBTPU_GCS_PATH" "$libtpu_path" + exit 0 + else + echo -e "\n\nError: You must provide a custom libtpu for libtpu-only mode.\n\n" + exit 1 + fi + fi +fi + +# Save the script folder path of maxtext +run_name_folder_path=$(pwd) + +# Uninstall existing jax, jaxlib and libtpu-nightly +pip3 show jax && pip3 uninstall -y jax +pip3 show jaxlib && pip3 uninstall -y jaxlib +pip3 show libtpu-nightly && pip3 uninstall -y libtpu-nightly + +# Delete custom libtpu if it exists +if [ -e "$libtpu_path" ]; then + rm "$libtpu_path" +fi + +if [[ "$MODE" == "stable" || ! -v MODE ]]; then +# Stable mode + if [[ $DEVICE == "tpu" ]]; then + echo "Installing stable jax, jaxlib for tpu" + if [[ -n "$JAX_VERSION" ]]; then + echo "Installing stable jax, jaxlib, libtpu version ${JAX_VERSION}" + pip3 install jax[tpu]==${JAX_VERSION} -f https://storage.googleapis.com/jax-releases/libtpu_releases.html + else + echo "Installing stable jax, jaxlib, libtpu for tpu" + pip3 install jax[tpu] -f https://storage.googleapis.com/jax-releases/libtpu_releases.html + fi + + if [[ -n "$LIBTPU_GCS_PATH" ]]; then + # Install custom libtpu + echo "Installing libtpu.so from $LIBTPU_GCS_PATH to $libtpu_path" + # Install required dependency + pip3 install -U crcmod + # Copy libtpu.so from GCS path + gsutil cp "$LIBTPU_GCS_PATH" "$libtpu_path" + fi + if [[ -n "$LIBTPU_GCS_PATH" ]]; then + # Install custom libtpu + echo "Installing libtpu.so from $LIBTPU_GCS_PATH to $libtpu_path" + # Install required dependency + pip3 install -U crcmod + # Copy libtpu.so from GCS path + gsutil cp "$LIBTPU_GCS_PATH" "$libtpu_path" + fi + elif [[ $DEVICE == "gpu" ]]; then + echo "Installing stable jax, jaxlib for NVIDIA gpu" + if [[ -n "$JAX_VERSION" ]]; then + echo "Installing stable jax, jaxlib ${JAX_VERSION}" + pip3 install -U "jax[cuda12_pip]==${JAX_VERSION}" -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html + else + echo "Installing stable jax, jaxlib, libtpu for NVIDIA gpu" + pip3 install -U "jax[cuda12_pip]" -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html + fi + fi +elif [[ $MODE == "nightly" ]]; then +# Nightly mode + if [[ $DEVICE == "gpu" ]]; then + echo "Installing jax-nightly, jaxlib-nightly" + # Install jax-nightly + pip3 install --pre -U jax -f https://storage.googleapis.com/jax-releases/jax_nightly_releases.html + # Install jaxlib-nightly + pip3 install -U --pre jaxlib -f https://storage.googleapis.com/jax-releases/jaxlib_nightly_cuda12_releases.html + elif [[ $DEVICE == "tpu" ]]; then + echo "Installing jax-nightly, jaxlib-nightly" + # Install jax-nightly + pip3 install --pre -U jax -f https://storage.googleapis.com/jax-releases/jax_nightly_releases.html + # Install jaxlib-nightly + pip3 install --pre -U jaxlib -f https://storage.googleapis.com/jax-releases/jaxlib_nightly_releases.html + + if [[ -n "$LIBTPU_GCS_PATH" ]]; then + # Install custom libtpu + echo "Installing libtpu.so from $LIBTPU_GCS_PATH to $libtpu_path" + # Install required dependency + pip3 install -U crcmod + # Copy libtpu.so from GCS path + gsutil cp "$LIBTPU_GCS_PATH" "$libtpu_path" + else + # Install libtpu-nightly + echo "Installing libtpu-nightly" + pip3 install libtpu-nightly -f https://storage.googleapis.com/jax-releases/libtpu_releases.html -U --pre + fi + echo "Installing nightly tensorboard plugin profile" + pip3 install tbp-nightly --upgrade + fi + echo "Installing nightly tensorboard plugin profile" + pip3 install tbp-nightly --upgrade +else + echo -e "\n\nError: You can only set MODE to [stable,nightly,libtpu-only].\n\n" + exit 1 +fi + +# Install dependencies from requirements.txt +cd $run_name_folder_path && pip install --upgrade pip && pip3 install -r requirements.txt diff --git a/maxtext-setup/maxtext/setup_gcsfuse.sh b/maxtext-setup/maxtext/setup_gcsfuse.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a0b133009c146bc5747c80f1c1ab3a24e28ea7f --- /dev/null +++ b/maxtext-setup/maxtext/setup_gcsfuse.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +# Copyright 2023 Google LLC +# +# 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. + +# Description: +# bash setup_gcsfuse.sh DATASET_GCS_BUCKET=maxtext-dataset MOUNT_PATH=dataset + +set -e + +# Set environment variables +for ARGUMENT in "$@"; do + IFS='=' read -r KEY VALUE <<< "$ARGUMENT" + export "$KEY"="$VALUE" + echo "$KEY"="$VALUE" +done + +if [[ -z ${DATASET_GCS_BUCKET} || -z ${MOUNT_PATH} ]]; then + echo "Please set arguments: DATASET_GCS_BUCKET and MOUNT_PATH" + exit 1 +fi + +if [[ "$DATASET_GCS_BUCKET" =~ gs:\/\/ ]] ; then + DATASET_GCS_BUCKET="${DATASET_GCS_BUCKET/gs:\/\//}" + echo "Removed gs:// from GCS bucket name, GCS bucket is $DATASET_GCS_BUCKET" +fi + +if [[ -d ${MOUNT_PATH} ]]; then + echo "$MOUNT_PATH exists, removing..." + fusermount -u $MOUNT_PATH || rm -rf $MOUNT_PATH +fi + +mkdir -p $MOUNT_PATH + +gcsfuse -o ro --implicit-dirs --http-client-timeout=5s --max-conns-per-host=2000 \ + --debug_fuse_errors --debug_fuse --debug_gcs --debug_invariants --debug_mutex \ + --log-file=$HOME/gcsfuse.json "$DATASET_GCS_BUCKET" "$MOUNT_PATH" diff --git a/maxtext-setup/maxtext/setup_with_retries.sh b/maxtext-setup/maxtext/setup_with_retries.sh new file mode 100644 index 0000000000000000000000000000000000000000..c0a76792f38d0f380ecf9a4da8b5ad7e10a19233 --- /dev/null +++ b/maxtext-setup/maxtext/setup_with_retries.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +max_attempts=5 +current_attempt=1 + +# Loop until setup succeeds or reaches the maximum number of attempts +while [ $current_attempt -le $max_attempts ]; do + echo "Attempt to run setup.sh $current_attempt:" + bash setup.sh "$@" + + # Check the exit status of run_setup + if [ $? -eq 0 ]; then + echo "Success for running setup on attempt $current_attempt!" + exit 0 + else + echo "Failed to run setup on attempt $current_attempt." + ((current_attempt++)) + sleep 5 # Short delay before next attempt + fi +done + +echo "All attempts to run setup failed. Exiting." +exit 1 \ No newline at end of file diff --git a/maxtext-setup/maxtext/unit_test_and_lint.sh b/maxtext-setup/maxtext/unit_test_and_lint.sh new file mode 100644 index 0000000000000000000000000000000000000000..d34f91b1ba604dc06226e8cf9f17c74f7b317eff --- /dev/null +++ b/maxtext-setup/maxtext/unit_test_and_lint.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# Copyright 2023 Google LLC +# +# 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. + +python3 -m pylint $(git ls-files '*.py') + +cd MaxText +python3 -m pytest