diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fp16_deprecated/loss_scaler.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fp16_deprecated/loss_scaler.py new file mode 100644 index 0000000000000000000000000000000000000000..63c68621abf624a4f16177142cfd89a3892f13a1 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fp16_deprecated/loss_scaler.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""For backward compatibility, we need the class definitions to deserialize.""" + +class LossScaler: + def __init__(self, scale=1): + self.cur_scale = scale + +class DynamicLossScaler: + def __init__(self, + init_scale=2**32, + scale_factor=2., + scale_window=1000, + min_scale=1, + delayed_shift=1, + consecutive_hysteresis=False): + self.cur_scale = init_scale + self.cur_iter = 0 + self.last_overflow_iter = -1 + self.scale_factor = scale_factor + self.scale_window = scale_window + self.min_scale = min_scale + self.delayed_shift = delayed_shift + self.cur_hysteresis = delayed_shift + self.consecutive_hysteresis = consecutive_hysteresis + diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/__init__.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b67fcae7769d0db97e4017c67cb23e55364ce3 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/__init__.py @@ -0,0 +1,109 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import pathlib +import subprocess + +from torch.utils import cpp_extension + +# Setting this param to a list has a problem of generating different +# compilation commands (with diferent order of architectures) and +# leading to recompilation of fused kernels. Set it to empty string +# to avoid recompilation and assign arch flags explicity in +# extra_cuda_cflags below +os.environ["TORCH_CUDA_ARCH_LIST"] = "" + + +def load(args): + + # Check if cuda 11 is installed for compute capability 8.0 + cc_flag = [] + _, bare_metal_major, _ = _get_cuda_bare_metal_version( + cpp_extension.CUDA_HOME) + if int(bare_metal_major) >= 11: + cc_flag.append('-gencode') + cc_flag.append('arch=compute_80,code=sm_80') + + # Build path + srcpath = pathlib.Path(__file__).parent.absolute() + buildpath = srcpath / 'build' + _create_build_dir(buildpath) + + # Helper function to build the kernels. + def _cpp_extention_load_helper(name, sources, extra_cuda_flags): + return cpp_extension.load( + name=name, + sources=sources, + build_directory=buildpath, + extra_cflags=['-O3',], + extra_cuda_cflags=['-O3', + '-gencode', 'arch=compute_70,code=sm_70', + '--use_fast_math'] + extra_cuda_flags + cc_flag, + verbose=(args.rank == 0) + ) + + # ============== + # Fused softmax. + # ============== + + if args.masked_softmax_fusion: + extra_cuda_flags = ['-U__CUDA_NO_HALF_OPERATORS__', + '-U__CUDA_NO_HALF_CONVERSIONS__', + '--expt-relaxed-constexpr', + '--expt-extended-lambda'] + + # Upper triangular softmax. + sources=[srcpath / 'scaled_upper_triang_masked_softmax.cpp', + srcpath / 'scaled_upper_triang_masked_softmax_cuda.cu'] + scaled_upper_triang_masked_softmax_cuda = _cpp_extention_load_helper( + "scaled_upper_triang_masked_softmax_cuda", + sources, extra_cuda_flags) + + # Masked softmax. + sources=[srcpath / 'scaled_masked_softmax.cpp', + srcpath / 'scaled_masked_softmax_cuda.cu'] + scaled_masked_softmax_cuda = _cpp_extention_load_helper( + "scaled_masked_softmax_cuda", sources, extra_cuda_flags) + + # ================================= + # Mixed precision fused layer norm. + # ================================= + + extra_cuda_flags = ['-maxrregcount=50'] + sources=[srcpath / 'layer_norm_cuda.cpp', + srcpath / 'layer_norm_cuda_kernel.cu'] + fused_mix_prec_layer_norm_cuda = _cpp_extention_load_helper( + "fused_mix_prec_layer_norm_cuda", sources, extra_cuda_flags) + + +def _get_cuda_bare_metal_version(cuda_dir): + raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], + universal_newlines=True) + output = raw_output.split() + release_idx = output.index("release") + 1 + release = output[release_idx].split(".") + bare_metal_major = release[0] + bare_metal_minor = release[1][0] + + return raw_output, bare_metal_major, bare_metal_minor + + +def _create_build_dir(buildpath): + try: + os.mkdir(buildpath) + except OSError: + if not os.path.isdir(buildpath): + print(f"Creation of the build directory {buildpath} failed") diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/compat.h b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/compat.h new file mode 100644 index 0000000000000000000000000000000000000000..92e7eb7723bdc9a7cf5d65bda3ba45775ef8c589 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/compat.h @@ -0,0 +1,31 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/*This code is copied fron NVIDIA apex: + * https://github.com/NVIDIA/apex + * with minor changes. */ + + + +#ifndef TORCH_CHECK +#define TORCH_CHECK AT_CHECK +#endif + +#ifdef VERSION_GE_1_3 +#define DATA_PTR data_ptr +#else +#define DATA_PTR data +#endif diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/layer_norm_cuda.cpp b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/layer_norm_cuda.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f28e7b4ad361b6f51579b35a77c7c0a42ab2841 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/layer_norm_cuda.cpp @@ -0,0 +1,201 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/*This code is copied fron NVIDIA apex: + * https://github.com/NVIDIA/apex + * with minor changes. */ + +#include +#include +#include +#include "compat.h" + +namespace { + +void compute_n1_n2( + at::Tensor input, + at::IntArrayRef normalized_shape, + int& n1, + int& n2) { + int idiff = input.ndimension() - normalized_shape.size(); + n2 = 1; + for (int i = 0; i < (int)normalized_shape.size(); ++i) { + assert( input.sizes()[i+idiff] == normalized_shape[i] ); + n2 *= normalized_shape[i]; + } + n1 = 1; + for (int i = 0; i < idiff; ++i) { + n1 *= input.sizes()[i]; + } +} + +void check_args( + at::IntArrayRef normalized_shape, + at::Tensor gamma, + at::Tensor beta + ) +{ + TORCH_CHECK(!gamma.defined() || gamma.sizes().equals(normalized_shape)); + TORCH_CHECK(!beta.defined() || beta.sizes().equals(normalized_shape)); +} + +void check_args( + at::Tensor input, + at::IntArrayRef normalized_shape, + int& n1, + int& n2 + ) +{ + int64_t normalized_ndim = normalized_shape.size(); + + if (normalized_ndim < 1) { + std::stringstream ss; + ss << "Expected normalized_shape to be at least 1-dimensional, i.e., " + << "containing at least one element, but got normalized_shape=" + << normalized_shape; + throw std::runtime_error(ss.str()); + } + + auto input_shape = input.sizes(); + auto input_ndim = input.dim(); + + if (input_ndim < normalized_ndim || + !input_shape.slice(input_ndim - normalized_ndim).equals(normalized_shape)) { + std::stringstream ss; + ss << "Given normalized_shape=" << normalized_shape + << ", expected input with shape [*"; + for (auto size : normalized_shape) { + ss << ", " << size; + } + ss << "], but got input of size" << input_shape; + throw std::runtime_error(ss.str()); + } + + compute_n1_n2(input,normalized_shape,n1,n2); +} + + +void check_args( + at::Tensor input, + at::IntArrayRef normalized_shape, + at::Tensor gamma, + at::Tensor beta, + int& n1, + int& n2 + ) +{ + check_args(input,normalized_shape,n1,n2); + check_args(normalized_shape,gamma,beta); +} +} + +void cuda_layer_norm( + at::Tensor* output, + at::Tensor* mean, + at::Tensor* invvar, + at::Tensor* input, + int n1, + int n2, + at::IntArrayRef normalized_shape, + at::Tensor* gamma, + at::Tensor* beta, + double epsilon); + +#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") +#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) + +std::vector layer_norm_affine( + at::Tensor input, + at::IntArrayRef normalized_shape, + at::Tensor gamma, + at::Tensor beta, + double epsilon) { + + CHECK_INPUT(input); + CHECK_INPUT(gamma); + CHECK_INPUT(beta); + int n1, n2; + check_args(input, normalized_shape, gamma, beta, n1, n2); + + at::Tensor output = at::empty_like( + input, gamma.options().dtype(gamma.scalar_type())); + at::Tensor mean = at::empty( + {n1}, input.options().dtype(at::ScalarType::Float)); + at::Tensor invvar = at::empty_like(mean); + + cuda_layer_norm(&output, &mean, &invvar, &input, n1, n2, + normalized_shape, &gamma, &beta, epsilon); + + return {output, mean, invvar}; + +} + + +void cuda_layer_norm_gradient( + at::Tensor* dout, + at::Tensor* mean, + at::Tensor* invvar, + at::Tensor* input, + int n1, + int n2, + at::IntArrayRef normalized_shape, + at::Tensor* gamma, + at::Tensor* beta, + double epsilon, + at::Tensor* grad_input, + at::Tensor* grad_gamma, + at::Tensor* grad_beta + ); + +std::vector layer_norm_gradient_affine( + at::Tensor dout, + at::Tensor mean, + at::Tensor invvar, + at::Tensor input, + at::IntArrayRef normalized_shape, + at::Tensor gamma, + at::Tensor beta, + double epsilon) { + + CHECK_INPUT(dout); + CHECK_INPUT(mean); + CHECK_INPUT(invvar); + CHECK_INPUT(input); + CHECK_INPUT(gamma); + CHECK_INPUT(beta); + int n1, n2; + check_args(input, normalized_shape, gamma, beta, n1, n2); + + at::Tensor grad_input = at::empty_like(input); + at::Tensor grad_gamma = at::empty_like(gamma); + at::Tensor grad_beta = at::empty_like(beta); + + cuda_layer_norm_gradient(&dout, &mean, &invvar, &input, n1, n2, + normalized_shape, &gamma, &beta, epsilon, + &grad_input, &grad_gamma, &grad_beta); + + return {grad_input, grad_gamma, grad_beta}; + +} + + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward_affine", &layer_norm_affine, + "LayerNorm forward (CUDA)"); + m.def("backward_affine", &layer_norm_gradient_affine, + "LayerNorm backward (CUDA)"); +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/layer_norm_cuda_kernel.cu b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/layer_norm_cuda_kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..91d533191506b939aae0fd304f0bb7e8c89895c2 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/layer_norm_cuda_kernel.cu @@ -0,0 +1,832 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/*This code is copied fron NVIDIA apex: + * https://github.com/NVIDIA/apex + * with minor changes. */ + +#include "ATen/ATen.h" +#include "ATen/AccumulateType.h" +#include "ATen/cuda/CUDAContext.h" +#include "ATen/cuda/DeviceUtils.cuh" + +#include +#include + +#include "type_shim.h" + +template __device__ +void cuWelfordOnlineSum( + const U curr, + U& mu, + U& sigma2, + U& count) +{ + count = count + U(1); + U delta = curr - mu; + U lmean = mu + delta / count; + mu = lmean; + U delta2 = curr - lmean; + sigma2 = sigma2 + delta * delta2; +} + +template __device__ +void cuChanOnlineSum( + const U muB, + const U sigma2B, + const U countB, + U& mu, + U& sigma2, + U& count) +{ + U delta = muB - mu; + U nA = count; + U nB = countB; + count = count + countB; + U nX = count; + if (nX > U(0)) { + nA = nA / nX; + nB = nB / nX; + mu = nA*mu + nB*muB; + sigma2 = sigma2 + sigma2B + delta * delta * nA * nB * nX; + } else { + mu = U(0); + sigma2 = U(0); + } +} + +template __device__ +void cuWelfordMuSigma2( + const T* __restrict__ vals, + const int n1, + const int n2, + const int i1, + U& mu, + U& sigma2, + U* buf) +{ + // Assumptions: + // 1) blockDim.x == warpSize + // 2) Tensor is contiguous + // 3) 2*blockDim.y*sizeof(U)+blockDim.y*sizeof(int) shared memory available. + // + // compute variance and mean over n2 + U count = U(0); + mu= U(0); + sigma2 = U(0); + if (i1 < n1) { + // one warp normalizes one n1 index, + // synchronization is implicit + // initialize with standard Welford algorithm + const int numx = blockDim.x * blockDim.y; + const int thrx = threadIdx.x + threadIdx.y * blockDim.x; + const T* lvals = vals + i1*n2; + int l = 4*thrx; + for (; l+3 < n2; l+=4*numx) { + for (int k = 0; k < 4; ++k) { + U curr = static_cast(lvals[l+k]); + cuWelfordOnlineSum(curr,mu,sigma2,count); + } + } + for (; l < n2; ++l) { + U curr = static_cast(lvals[l]); + cuWelfordOnlineSum(curr,mu,sigma2,count); + } + // intra-warp reductions + for (int l = 0; l <= 4; ++l) { + int srcLaneB = (threadIdx.x+(1<(muB,sigma2B,countB,mu,sigma2,count); + } + // threadIdx.x == 0 has correct values for each warp + // inter-warp reductions + if (blockDim.y > 1) { + U* ubuf = (U*)buf; + U* ibuf = (U*)(ubuf + blockDim.y); + for (int offset = blockDim.y/2; offset > 0; offset /= 2) { + // upper half of warps write to shared + if (threadIdx.x == 0 && threadIdx.y >= offset && threadIdx.y < 2*offset) { + const int wrt_y = threadIdx.y - offset; + ubuf[2*wrt_y] = mu; + ubuf[2*wrt_y+1] = sigma2; + ibuf[wrt_y] = count; + } + __syncthreads(); + // lower half merges + if (threadIdx.x == 0 && threadIdx.y < offset) { + U muB = ubuf[2*threadIdx.y]; + U sigma2B = ubuf[2*threadIdx.y+1]; + U countB = ibuf[threadIdx.y]; + cuChanOnlineSum(muB,sigma2B,countB,mu,sigma2,count); + } + __syncthreads(); + } + // threadIdx.x = 0 && threadIdx.y == 0 only thread that has correct values + if (threadIdx.x == 0 && threadIdx.y == 0) { + ubuf[0] = mu; + ubuf[1] = sigma2; + } + __syncthreads(); + mu = ubuf[0]; + sigma2 = ubuf[1]/U(n2); + // don't care about final value of count, we know count == n2 + } else { + mu = WARP_SHFL(mu, 0); + sigma2 = WARP_SHFL(sigma2/U(n2), 0); + } + } +} + +template<> __device__ +void cuWelfordMuSigma2( + const at::Half* __restrict__ vals, + const int n1, + const int n2, + const int i1, + float& mu, + float& sigma2, + float* buf) +{ + // Assumptions: + // 1) blockDim.x == warpSize + // 2) Tensor is contiguous + // 3) 2*blockDim.y*sizeof(U)+blockDim.y*sizeof(int) shared memory available. + // + // compute variance and mean over n2 + float count = 0.0f; + mu= float(0); + sigma2 = float(0); + if (i1 < n1) { + // one warp normalizes one n1 index, + // synchronization is implicit + // initialize with standard Welford algorithm + const int numx = blockDim.x * blockDim.y; + const int thrx = threadIdx.x + threadIdx.y * blockDim.x; + const at::Half* lvals = vals + i1*n2; + int l = 8*thrx; + if ((((size_t)lvals)&3) != 0) { + // 16 bit alignment + // first thread consumes first point + if (thrx == 0) { + float curr = static_cast(lvals[0]); + cuWelfordOnlineSum(curr,mu,sigma2,count); + } + ++l; + } + // at this point, lvals[l] are 32 bit aligned for all threads. + for (; l+7 < n2; l+=8*numx) { + for (int k = 0; k < 8; k+=2) { + float2 curr = __half22float2(*((__half2*)(lvals+l+k))); + cuWelfordOnlineSum(curr.x,mu,sigma2,count); + cuWelfordOnlineSum(curr.y,mu,sigma2,count); + } + } + for (; l < n2; ++l) { + float curr = static_cast(lvals[l]); + cuWelfordOnlineSum(curr,mu,sigma2,count); + } + // intra-warp reductions + for (int l = 0; l <= 4; ++l) { + int srcLaneB = (threadIdx.x+(1< 1) { + float* ubuf = (float*)buf; + float* ibuf = (float*)(ubuf + blockDim.y); + for (int offset = blockDim.y/2; offset > 0; offset /= 2) { + // upper half of warps write to shared + if (threadIdx.x == 0 && threadIdx.y >= offset && threadIdx.y < 2*offset) { + const int wrt_y = threadIdx.y - offset; + ubuf[2*wrt_y] = mu; + ubuf[2*wrt_y+1] = sigma2; + ibuf[wrt_y] = count; + } + __syncthreads(); + // lower half merges + if (threadIdx.x == 0 && threadIdx.y < offset) { + float muB = ubuf[2*threadIdx.y]; + float sigma2B = ubuf[2*threadIdx.y+1]; + float countB = ibuf[threadIdx.y]; + cuChanOnlineSum(muB,sigma2B,countB,mu,sigma2,count); + } + __syncthreads(); + } + // threadIdx.x = 0 && threadIdx.y == 0 only thread that has correct values + if (threadIdx.x == 0 && threadIdx.y == 0) { + ubuf[0] = mu; + ubuf[1] = sigma2; + } + __syncthreads(); + mu = ubuf[0]; + sigma2 = ubuf[1]/float(n2); + // don't care about final value of count, we know count == n2 + } else { + mu = WARP_SHFL(mu, 0); + sigma2 = WARP_SHFL(sigma2/float(n2), 0); + } + } +} + +template U rsqrt(U v) { + return U(1) / sqrt(v); +} +template<> float rsqrt(float v) { + return rsqrtf(v); +} +template<> double rsqrt(double v) { + return rsqrt(v); +} + +namespace { +// This is the un-specialized struct. Note that we prevent instantiation of this +// struct by putting an undefined symbol in the function body so it won't compile. +// template +// struct SharedMemory +// { +// // Ensure that we won't compile any un-specialized types +// __device__ T *getPointer() +// { +// extern __device__ void error(void); +// error(); +// return NULL; +// } +// }; +// https://github.com/NVIDIA/apex/issues/246 +template +struct SharedMemory; + +template <> +struct SharedMemory +{ + __device__ float *getPointer() + { + extern __shared__ float s_float[]; + return s_float; + } +}; + +} + +template __global__ +void cuApplyLayerNorm( + V* __restrict__ output_vals, + U* __restrict__ mean, + U* __restrict__ invvar, + const T* __restrict__ vals, + const int n1, + const int n2, + const U epsilon, + const V* __restrict__ gamma, + const V* __restrict__ beta + ) +{ + // Assumptions: + // 1) blockDim.x == warpSize + // 2) Tensors are contiguous + // + for (auto i1=blockIdx.y; i1 < n1; i1 += gridDim.y) { + SharedMemory shared; + U* buf = shared.getPointer(); + U mu,sigma2; + cuWelfordMuSigma2(vals,n1,n2,i1,mu,sigma2,buf); + const T* lvals = vals + i1*n2; + V* ovals = output_vals + i1*n2; + U c_invvar = rsqrt(sigma2 + epsilon); + const int numx = blockDim.x * blockDim.y; + const int thrx = threadIdx.x + threadIdx.y * blockDim.x; + if (gamma != NULL && beta != NULL) { + for (int i = thrx; i < n2; i+=numx) { + U curr = static_cast(lvals[i]); + ovals[i] = gamma[i] * static_cast(c_invvar * (curr - mu)) + beta[i]; + } + } else { + for (int i = thrx; i < n2; i+=numx) { + U curr = static_cast(lvals[i]); + ovals[i] = static_cast(c_invvar * (curr - mu)); + } + } + if (threadIdx.x == 0 && threadIdx.y == 0) { + mean[i1] = mu; + invvar[i1] = c_invvar; + } + __syncthreads(); + } +} + +template __device__ +void cuLoadWriteStridedInputs( + const int i1_block, + const int thr_load_row_off, + const int thr_load_col_off, + const int i2_off, + const int row_stride, + U* warp_buf1, + U* warp_buf2, + const T* input, + const V* dout, + const int i1_end, + const int n2, + const U* __restrict__ mean, + const U* __restrict__ invvar + ) +{ + int i1 = i1_block+thr_load_row_off; + if (i1 < i1_end) { + U curr_mean = mean[i1]; + U curr_invvar = invvar[i1]; + for (int k = 0; k < blockDim.y; ++k) { + int i2 = i2_off + k; + int load_idx = i1*n2+i2; + int write_idx = thr_load_row_off*row_stride+thr_load_col_off+k; + if (i2(input[load_idx]); + U curr_dout = static_cast(dout[load_idx]); + warp_buf1[write_idx] = curr_dout; + warp_buf2[write_idx] = curr_dout * (curr_input - curr_mean) * curr_invvar; + } else { + warp_buf1[write_idx] = U(0); + warp_buf2[write_idx] = U(0); + } + } + } else { + for (int k = 0; k < blockDim.y; ++k) { + int write_idx = thr_load_row_off*row_stride+thr_load_col_off+k; + warp_buf1[write_idx] = U(0); + warp_buf2[write_idx] = U(0); + } + } +} + +template __device__ +void cuLoadAddStridedInputs( + const int i1_block, + const int thr_load_row_off, + const int thr_load_col_off, + const int i2_off, + const int row_stride, + U* warp_buf1, + U* warp_buf2, + const T* input, + const V* dout, + const int i1_end, + const int n2, + const U* __restrict__ mean, + const U* __restrict__ invvar + ) +{ + int i1 = i1_block+thr_load_row_off; + if (i1 < i1_end) { + U curr_mean = mean[i1]; + U curr_invvar = invvar[i1]; + for (int k = 0; k < blockDim.y; ++k) { + int i2 = i2_off + k; + int load_idx = i1*n2+i2; + int write_idx = thr_load_row_off*row_stride+thr_load_col_off+k; + if (i2(input[load_idx]); + U curr_dout = static_cast(dout[load_idx]); + warp_buf1[write_idx] += curr_dout; + warp_buf2[write_idx] += curr_dout * (curr_input - curr_mean) * curr_invvar; + } + } + } +} + +template __global__ +void cuComputePartGradGammaBeta( + const V* __restrict__ dout, + const T* __restrict__ input, + const int n1, + const int n2, + const U* __restrict__ mean, + const U* __restrict__ invvar, + U epsilon, + U* part_grad_gamma, + U* part_grad_beta) +{ + const int numsegs_n1 = (n1+blockDim.y*blockDim.y-1) / (blockDim.y*blockDim.y); + const int segs_per_block = (numsegs_n1 + gridDim.y - 1) / gridDim.y; + const int i1_beg = blockIdx.y * segs_per_block * blockDim.y*blockDim.y; + const int i1_beg_plus_one = (blockIdx.y+1) * segs_per_block * blockDim.y*blockDim.y; + const int i1_end = i1_beg_plus_one < n1 ? i1_beg_plus_one : n1; + const int row_stride = blockDim.x+1; + const int thr_load_col_off = (threadIdx.x*blockDim.y)&(blockDim.x-1); + const int thr_load_row_off = (threadIdx.x*blockDim.y)/blockDim.x + threadIdx.y*blockDim.y; + const int i2_off = blockIdx.x * blockDim.x + thr_load_col_off; + SharedMemory shared; + U* buf = shared.getPointer(); // buf has at least blockDim.x * blockDim.y * blockDim.y + (blockDim.y - 1)*(blockDim.x/blockDim.y) elements + U* warp_buf1 = (U*)buf; + U* warp_buf2 = warp_buf1 + blockDim.y * blockDim.y * row_stride; + // compute partial sums from strided inputs + // do this to increase number of loads in flight + cuLoadWriteStridedInputs(i1_beg,thr_load_row_off,thr_load_col_off,i2_off,row_stride,warp_buf1,warp_buf2,input,dout,i1_end,n2,mean,invvar); + for (int i1_block = i1_beg+blockDim.y*blockDim.y; i1_block < i1_end; i1_block+=blockDim.y*blockDim.y) { + cuLoadAddStridedInputs(i1_block,thr_load_row_off,thr_load_col_off,i2_off,row_stride,warp_buf1,warp_buf2,input,dout,i1_end,n2,mean,invvar); + } + __syncthreads(); + // inter-warp reductions + // sum within each warp + U acc1 = U(0); + U acc2 = U(0); + for (int k = 0; k < blockDim.y; ++k) { + int row1 = threadIdx.y + k*blockDim.y; + int idx1 = row1*row_stride + threadIdx.x; + acc1 += warp_buf1[idx1]; + acc2 += warp_buf2[idx1]; + } + warp_buf1[threadIdx.y*row_stride+threadIdx.x] = acc1; + warp_buf2[threadIdx.y*row_stride+threadIdx.x] = acc2; + __syncthreads(); + // sum all warps + for (int offset = blockDim.y/2; offset > 1; offset /= 2) { + if (threadIdx.y < offset) { + int row1 = threadIdx.y; + int row2 = threadIdx.y + offset; + int idx1 = row1*row_stride + threadIdx.x; + int idx2 = row2*row_stride + threadIdx.x; + warp_buf1[idx1] += warp_buf1[idx2]; + warp_buf2[idx1] += warp_buf2[idx2]; + } + __syncthreads(); + } + int i2 = blockIdx.x * blockDim.x + threadIdx.x; + if (threadIdx.y == 0 && i2 < n2) { + int row1 = threadIdx.y; + int row2 = threadIdx.y + 1; + int idx1 = row1*row_stride + threadIdx.x; + int idx2 = row2*row_stride + threadIdx.x; + part_grad_beta[blockIdx.y*n2+i2] = warp_buf1[idx1] + warp_buf1[idx2]; + part_grad_gamma[blockIdx.y*n2+i2] = warp_buf2[idx1] + warp_buf2[idx2]; + } +} + +template __global__ +void cuComputeGradGammaBeta( + const U* part_grad_gamma, + const U* part_grad_beta, + const int part_size, + const int n1, + const int n2, + V* grad_gamma, + V* grad_beta) +{ + // sum partial gradients for gamma and beta + SharedMemory shared; + U* buf = shared.getPointer(); + int i2 = blockIdx.x * blockDim.x + threadIdx.x; + if (i2 < n2) { + // each warp does sequential reductions until reduced part_size is num_warps + int num_warp_reductions = part_size / blockDim.y; + U sum_gamma = U(0); + U sum_beta = U(0); + const U* part_grad_gamma_ptr = part_grad_gamma + threadIdx.y * num_warp_reductions * n2 + i2; + const U* part_grad_beta_ptr = part_grad_beta + threadIdx.y * num_warp_reductions * n2 + i2; + for (int warp_offset = 0; warp_offset < num_warp_reductions; ++warp_offset) { + sum_gamma += part_grad_gamma_ptr[warp_offset*n2]; + sum_beta += part_grad_beta_ptr[warp_offset*n2]; + } + // inter-warp reductions + const int nbsize3 = blockDim.x * blockDim.y / 2; + for (int offset = blockDim.y/2; offset >= 1; offset /= 2) { + // top half write to shared memory + if (threadIdx.y >= offset && threadIdx.y < 2*offset) { + const int write_idx = (threadIdx.y - offset) * blockDim.x + threadIdx.x; + buf[write_idx] = sum_gamma; + buf[write_idx+nbsize3] = sum_beta; + } + __syncthreads(); + // bottom half sums + if (threadIdx.y < offset) { + const int read_idx = threadIdx.y * blockDim.x + threadIdx.x; + sum_gamma += buf[read_idx]; + sum_beta += buf[read_idx+nbsize3]; + } + __syncthreads(); + } + // write out fully summed gradients + if (threadIdx.y == 0) { + grad_gamma[i2] = sum_gamma; + grad_beta[i2] = sum_beta; + } + } +} + +template __global__ +void cuComputeGradInput( + const V* __restrict__ dout, + const T* __restrict__ input, + const int n1, + const int n2, + const U* __restrict__ mean, + const U* __restrict__ invvar, + U epsilon, + const V* gamma, + T* grad_input) +{ + for (auto i1=blockIdx.y; i1 < n1; i1 += gridDim.y) { + U sum_loss1 = U(0); + U sum_loss2 = U(0); + const U c_mean = mean[i1]; + const U c_invvar = invvar[i1]; + const T* k_input = input + i1*n2; + const V* k_dout = dout + i1*n2; + const int numx = blockDim.x * blockDim.y; + const int thrx = threadIdx.x + threadIdx.y * blockDim.x; + if (gamma != NULL) { + int l = 4*thrx; + for (; l+3 < n2; l+=4*numx) { + for (int k = 0; k < 4; ++k) { + const U c_h = static_cast(k_input[l+k]); + const U c_loss = static_cast(k_dout[l+k]); + sum_loss1 += c_loss * gamma[l+k]; + sum_loss2 += c_loss * gamma[l+k] * (c_h - c_mean) * c_invvar; + } + } + for (; l < n2; ++l) { + const U c_h = static_cast(k_input[l]); + const U c_loss = static_cast(k_dout[l]); + sum_loss1 += c_loss * gamma[l]; + sum_loss2 += c_loss * gamma[l] * (c_h - c_mean) * c_invvar; + } + } else { + int l = 4*thrx; + for (; l+3 < n2; l+=4*numx) { + for (int k = 0; k < 4; ++k) { + const U c_h = static_cast(k_input[l+k]); + const U c_loss = static_cast(k_dout[l+k]); + sum_loss1 += c_loss; + sum_loss2 += c_loss * (c_h - c_mean) * c_invvar; + } + } + for (; l < n2; ++l) { + const U c_h = static_cast(k_input[l]); + const U c_loss = static_cast(k_dout[l]); + sum_loss1 += c_loss; + sum_loss2 += c_loss * (c_h - c_mean) * c_invvar; + } + } + // intra-warp reductions + for (int mask = blockDim.x/2; mask > 0; mask /= 2) { + sum_loss1 += WARP_SHFL_XOR(sum_loss1, mask); + sum_loss2 += WARP_SHFL_XOR(sum_loss2, mask); + } + // inter-warp reductions + if (blockDim.y > 1) { + SharedMemory shared; + U* buf = shared.getPointer(); + for (int offset = blockDim.y/2; offset > 0; offset /= 2) { + // upper half of warps write to shared + if (threadIdx.y >= offset && threadIdx.y < 2*offset) { + const int wrt_i = (threadIdx.y - offset) * blockDim.x + threadIdx.x; + buf[2*wrt_i] = sum_loss1; + buf[2*wrt_i+1] = sum_loss2; + } + __syncthreads(); + // lower half merges + if (threadIdx.y < offset) { + const int read_i = threadIdx.y * blockDim.x + threadIdx.x; + sum_loss1 += buf[2*read_i]; + sum_loss2 += buf[2*read_i+1]; + } + __syncthreads(); + } + if (threadIdx.y == 0) { + buf[2*threadIdx.x] = sum_loss1; + buf[2*threadIdx.x+1] = sum_loss2; + } + __syncthreads(); + if (threadIdx.y !=0) { + sum_loss1 = buf[2*threadIdx.x]; + sum_loss2 = buf[2*threadIdx.x+1]; + } + } + // all threads now have the two sums over l + U fH = (U)n2; + U term1 = (U(1) / fH) * c_invvar; + T* k_grad_input = grad_input + i1*n2; + if (gamma != NULL) { + for (int l = thrx; l < n2; l+=numx) { + const U c_h = static_cast(k_input[l]); + const U c_loss = static_cast(k_dout[l]); + U f_grad_input = fH * c_loss * gamma[l]; + f_grad_input -= sum_loss1; + f_grad_input -= (c_h - c_mean) * c_invvar * sum_loss2; + f_grad_input *= term1; + k_grad_input[l] = static_cast(f_grad_input); + } + } else { + for (int l = thrx; l < n2; l+=numx) { + const U c_h = static_cast(k_input[l]); + const U c_loss = static_cast(k_dout[l]); + U f_grad_input = fH * c_loss; + f_grad_input -= sum_loss1; + f_grad_input -= (c_h - c_mean) * c_invvar * sum_loss2; + f_grad_input *= term1; + k_grad_input[l] = static_cast(f_grad_input); + } + } + // prevent race where buf is written again before reads are done + __syncthreads(); + } +} + + + + +template +void HostApplyLayerNorm( + V* output, + U* mean, + U* invvar, + const T* input, + int n1, + int n2, + double epsilon, + const V* gamma, + const V* beta + ) +{ + auto stream = at::cuda::getCurrentCUDAStream().stream(); + const dim3 threads(32,4,1); + const uint64_t maxGridY = + at::cuda::getCurrentDeviceProperties()->maxGridSize[1]; + const dim3 blocks(1, std::min((uint64_t)n1, maxGridY), 1); + int nshared = + threads.y > 1 ? + threads.y*sizeof(U)+(threads.y/2)*sizeof(U) : + 0; + cuApplyLayerNorm<<>>( + output, + mean, + invvar, + input, + n1,n2, + U(epsilon), + gamma,beta); +} + + +void cuda_layer_norm( + at::Tensor* output, + at::Tensor* mean, + at::Tensor* invvar, + at::Tensor* input, + int n1, + int n2, + #ifdef VERSION_GE_1_1 + at::IntArrayRef normalized_shape, + #else + at::IntList normalized_shape, + #endif + at::Tensor* gamma, + at::Tensor* beta, + double epsilon) +{ + using namespace at; + DISPATCH_FLOAT_HALF_AND_BFLOAT_INOUT_TYPES( + input->scalar_type(), output->scalar_type(), "cuda_layer_norm_kernel", + HostApplyLayerNorm( + output->DATA_PTR(), + mean->DATA_PTR(), + invvar->DATA_PTR(), + input->DATA_PTR(), + n1,n2, + epsilon, + gamma != NULL ? gamma->DATA_PTR() : NULL, + beta != NULL ? beta->DATA_PTR() : NULL); + ) +} + + +template +void HostLayerNormGradient( + const V* dout, + const U* mean, + const U* invvar, + at::Tensor* input, + int n1, + int n2, + const V* gamma, + const V* beta, + double epsilon, + T* grad_input, + V* grad_gamma, + V* grad_beta + ) +{ + auto stream = at::cuda::getCurrentCUDAStream().stream(); + + if (gamma != NULL && beta != NULL) { + // compute grad_gamma(j) and grad_beta(j) + const int part_size = 16; + const dim3 threads2(32,4,1); + const dim3 blocks2((n2+threads2.x-1)/threads2.x,part_size,1); + const int nshared2_a = 2 * sizeof(U) * threads2.y * threads2.y * + (threads2.x + 1); + const int nshared2_b = threads2.x * threads2.y * sizeof(U); + const int nshared2 = nshared2_a > nshared2_b ? nshared2_a : nshared2_b; + at::Tensor part_grad_gamma = at::empty( + {part_size,n2}, input->options().dtype(at::ScalarType::Float)); + at::Tensor part_grad_beta = at::empty_like(part_grad_gamma); + cuComputePartGradGammaBeta<<>>( + dout, + input->DATA_PTR(), + n1,n2, + mean, + invvar, + U(epsilon), + part_grad_gamma.DATA_PTR(), + part_grad_beta.DATA_PTR()); + + const dim3 threads3(32,8,1); + const dim3 blocks3((n2+threads2.x-1)/threads2.x,1,1); + const int nshared3 = threads3.x * threads3.y * sizeof(U); + cuComputeGradGammaBeta<<>>( + part_grad_gamma.DATA_PTR(), + part_grad_beta.DATA_PTR(), + part_size, + n1,n2, + grad_gamma, + grad_beta); + } + + // compute grad_input + const uint64_t maxGridY = + at::cuda::getCurrentDeviceProperties()->maxGridSize[1]; + const dim3 blocks1(1, std::min((uint64_t)n1, maxGridY), 1); + const dim3 threads1(32,4,1); + int nshared = + threads1.y > 1 ? + threads1.y*threads1.x*sizeof(U) : + 0; + cuComputeGradInput<<>>( + dout, + input->DATA_PTR(), + n1,n2, + mean, + invvar, + U(epsilon), + gamma, + grad_input); +} + + +void cuda_layer_norm_gradient( + at::Tensor* dout, + at::Tensor* mean, + at::Tensor* invvar, + at::Tensor* input, + int n1, + int n2, + #ifdef VERSION_GE_1_1 + at::IntArrayRef normalized_shape, + #else + at::IntList normalized_shape, + #endif + at::Tensor* gamma, + at::Tensor* beta, + double epsilon, + at::Tensor* grad_input, + at::Tensor* grad_gamma, + at::Tensor* grad_beta) +{ + using namespace at; + DISPATCH_FLOAT_HALF_AND_BFLOAT_INOUT_TYPES( + input->scalar_type(), gamma->scalar_type(), + "cuda_layer_norm_gradient_kernel", + HostLayerNormGradient( + dout->DATA_PTR(), + mean->DATA_PTR(), + invvar->DATA_PTR(), + input, + n1,n2, + // TMJ pass NULL argument for gamma, beta, grad_gamma and grad_beta + // if gamma Tensor is NULL on input. + gamma != NULL ? gamma->DATA_PTR() : NULL, + gamma != NULL ? beta->DATA_PTR() : NULL, + epsilon, + grad_input->DATA_PTR(), + gamma != NULL ? grad_gamma->DATA_PTR() : NULL, + gamma != NULL ? grad_beta->DATA_PTR() : NULL); + ) +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_masked_softmax.cpp b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_masked_softmax.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d5334710cf9b5fa3e0419439d19c1eca0cbfe46f --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_masked_softmax.cpp @@ -0,0 +1,77 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +namespace multihead_attn { +namespace fused_softmax { +namespace scaled_masked_softmax { + +torch::Tensor fwd_cuda( + torch::Tensor const& input, + torch::Tensor const& mask, + float scale_factor); + +torch::Tensor bwd_cuda( + torch::Tensor const& output_grads, + torch::Tensor const& softmax_results, + float scale_factor); + +torch::Tensor fwd( + torch::Tensor const& input, + torch::Tensor const& mask, + float scale_factor) { + AT_ASSERTM(input.dim() == 4, "expected 4D tensor"); + AT_ASSERTM((input.scalar_type() == at::ScalarType::Half) || + (input.scalar_type() == at::ScalarType::BFloat16), + "Only fp16 and bf16 are supported"); + AT_ASSERTM(mask.dim() == 4, "expected 4D tensor"); + + return fwd_cuda(input, mask, scale_factor); +} + +torch::Tensor bwd( + torch::Tensor const& output_grads, + torch::Tensor const& softmax_results, + float scale_factor) { + + AT_ASSERTM(output_grads.dim() == 4, "expected 3D tensor"); + AT_ASSERTM(softmax_results.dim() == 4, "expected 3D tensor"); + + AT_ASSERTM((output_grads.scalar_type() == at::ScalarType::Half) || + (output_grads.scalar_type() == at::ScalarType::BFloat16), + "Only fp16 and bf16 are supported"); + AT_ASSERTM((softmax_results.scalar_type() == at::ScalarType::Half) || + (softmax_results.scalar_type() == at::ScalarType::BFloat16), + "Only fp16 and bf16 are supported"); + + return bwd_cuda(output_grads, softmax_results, scale_factor); +} + +} // end namespace scaled_masked_softmax +} // end namespace fused_softmax +} // end namespace multihead_attn + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward", + &multihead_attn::fused_softmax::scaled_masked_softmax::fwd, + "Self Multihead Attention scaled, time masked softmax -- Forward."); + m.def("backward", + &multihead_attn::fused_softmax::scaled_masked_softmax::bwd, + "Self Multihead Attention scaled, time masked softmax -- Backward."); +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_masked_softmax.h b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_masked_softmax.h new file mode 100644 index 0000000000000000000000000000000000000000..78e97e4ec60d545a93bf628e6a0135aca707baf5 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_masked_softmax.h @@ -0,0 +1,492 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +template +__device__ __inline__ void copy_vector(Datatype *dst, const Datatype *src); + +template <> +__device__ __inline__ void copy_vector(c10::BFloat16 *dst, const c10::BFloat16 *src) { *dst = *src; } + +template <> +__device__ __inline__ void copy_vector(c10::BFloat16 *dst, const c10::BFloat16 *src) { *((float2*) dst) = *((float2*) src); } + +template <> +__device__ __inline__ void copy_vector(c10::Half *dst, const c10::Half *src) { *dst = *src; } + +template <> +__device__ __inline__ void copy_vector(c10::Half *dst, const c10::Half *src) { *((float2*) dst) = *((float2*) src); } + +template <> +__device__ __inline__ void copy_vector(uint8_t *dst, const uint8_t *src) { *dst = *src; } + +template <> +__device__ __inline__ void copy_vector(uint8_t *dst, const uint8_t *src) {*((half2*) dst) = *((half2*) src); } + +int log2_ceil(int value) { + int log2_value = 0; + while ((1 << log2_value) < value) ++log2_value; + return log2_value; +} + +template +struct Add { + __device__ __forceinline__ T operator()(T a, T b) const { + return a + b; + } +}; + +template +struct Max { + __device__ __forceinline__ T operator()(T a, T b) const { + return a < b ? b : a; + } +}; + +template +__device__ __forceinline__ T WARP_SHFL_XOR_NATIVE(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if CUDA_VERSION >= 9000 + return __shfl_xor_sync(mask, value, laneMask, width); +#else + return __shfl_xor(value, laneMask, width); +#endif +} + +template class ReduceOp> +__device__ __forceinline__ void warp_reduce(acc_t* sum) { + ReduceOp r; + #pragma unroll + for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + acc_t b = WARP_SHFL_XOR_NATIVE(sum[i], offset, WARP_SIZE); + sum[i] = r(sum[i], b); + } + } +} + +/* + * Extended softmax (from native aten pytorch) with following additional features + * 1) input scaling + * 2) Explicit masking + */ +template +__global__ void scaled_masked_softmax_warp_forward( + output_t *dst, + const input_t *src, + const uint8_t *mask, + const acc_t scale, + int micro_batch_size, + int element_count, + int pad_batches) +{ + // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and + // warp_size of method warp_softmax_forward_kernel. + constexpr int next_power_of_two = 1 << log2_elements; + constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; + constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; + constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; + constexpr int ELEMENTS_PER_LDG_STG = 4; + + // blockDim/threadIdx = (WARP_SIZE, WARPS_PER_BLOCK, ) + // gridDim/blockIdx = (seq_len, attn_heads, batches) + int first_batch = (blockDim.y * (blockIdx.x + gridDim.x * (blockIdx.y + gridDim.y * blockIdx.z))+ threadIdx.y) * WARP_BATCH; + int pad_first_batch = 0; + if (pad_batches != 1) { // bert style + pad_first_batch = (blockDim.y * (blockIdx.x + gridDim.x * blockIdx.z) + threadIdx.y) * WARP_BATCH; + } else { // gpt2 style + pad_first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; + } + + // micro_batch_size might not be a multiple of WARP_BATCH. Check how + // many batches have to computed within this WARP. + int local_batches = micro_batch_size - first_batch; + if (local_batches > WARP_BATCH) + local_batches = WARP_BATCH; + + // there might be multiple batches per warp. compute the index within the batch + int local_idx = threadIdx.x; + + src += first_batch * element_count + ELEMENTS_PER_LDG_STG * local_idx; + dst += first_batch * element_count + ELEMENTS_PER_LDG_STG * local_idx; + mask += pad_first_batch * element_count + ELEMENTS_PER_LDG_STG * local_idx; + + // load data from global memory + acc_t elements[WARP_BATCH][WARP_ITERATIONS]; + input_t temp_data[ELEMENTS_PER_LDG_STG]; + uint8_t temp_mask[ELEMENTS_PER_LDG_STG]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + int batch_element_count = (i >= local_batches) ? 0 : element_count; + + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) { + int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; + + if (element_index < batch_element_count) { + int itr_idx = i*element_count+it*WARP_SIZE; + copy_vector(temp_data, src + itr_idx); + copy_vector(temp_mask, mask + itr_idx); + + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + if (temp_mask[element] != 1) { + elements[i][it + element] = (acc_t)temp_data[element] * scale; + } else { + elements[i][it + element] = -10000.0; + } + } + } else { + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + elements[i][it + element] = -std::numeric_limits::infinity(); + } + } + } + } + + // compute max_value + acc_t max_value[WARP_BATCH]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + max_value[i] = elements[i][0]; + #pragma unroll + for (int it = 1; it < WARP_ITERATIONS; ++it) { + max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; + } + } + warp_reduce(max_value); + + acc_t sum[WARP_BATCH] { 0.0f }; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; ++it) { + elements[i][it] = std::exp((elements[i][it] - max_value[i])); + sum[i] += elements[i][it]; + } + } + warp_reduce(sum); + + // store result + output_t out[ELEMENTS_PER_LDG_STG]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + if (i >= local_batches) + break; + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) { + int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; + if (element_index < element_count) { + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + out[element] = elements[i][it + element] / sum[i]; + } + copy_vector(dst + i * element_count + it * WARP_SIZE, out); + } else { + break; + } + } + } +} + +template +__global__ void scaled_masked_softmax_warp_backward( + output_t *gradInput, + input_t *grad, + const input_t *output, + acc_t scale, + int micro_batch_size, + int element_count) +{ + // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and + // warp_size of method warp_softmax_backward_kernel. + constexpr int next_power_of_two = 1 << log2_elements; + constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; + constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; + constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; + constexpr int ELEMENTS_PER_LDG_STG = 4; + + // blockDim/threadIdx = (WARP_SIZE, WARPS_PER_BLOCK, ) + // gridDim/blockIdx = (seq_len, attn_heads, batches) + int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; + + // micro_batch_size might not be a multiple of WARP_BATCH. Check how + // many batches have to computed within this WARP. + int local_batches = micro_batch_size - first_batch; + if (local_batches > WARP_BATCH) + local_batches = WARP_BATCH; + + // there might be multiple batches per warp. compute the index within the batch + int local_idx = threadIdx.x; + + // the first element to process by the current thread + int thread_offset = first_batch * element_count + ELEMENTS_PER_LDG_STG * local_idx; + grad += thread_offset; + output += thread_offset; + gradInput += thread_offset; + + // load data from global memory + acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] { 0.0f }; + acc_t output_reg[WARP_BATCH][WARP_ITERATIONS] { 0.0f }; + input_t temp_grad[ELEMENTS_PER_LDG_STG]; + input_t temp_output[ELEMENTS_PER_LDG_STG]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + int batch_element_count = (i >= local_batches) ? 0 : element_count; + + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) { + int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; + if (element_index < batch_element_count) { + copy_vector(temp_grad, grad + i * element_count + it * WARP_SIZE); + copy_vector(temp_output, output + i * element_count + it * WARP_SIZE); + + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + output_reg[i][it + element] = (acc_t)temp_output[element]; + } + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + grad_reg[i][it + element] = (acc_t)temp_grad[element] * output_reg[i][it + element]; + } + } + } + } + + acc_t sum[WARP_BATCH]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + sum[i] = grad_reg[i][0]; + #pragma unroll + for (int it = 1; it < WARP_ITERATIONS; ++it) { + sum[i] += grad_reg[i][it]; + } + } + warp_reduce(sum); + + // store result + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + if (i >= local_batches) + break; + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) { + int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; + if (element_index < element_count) { + // compute gradients + output_t out[ELEMENTS_PER_LDG_STG]; + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + out[element] = (output_t)(scale * (grad_reg[i][it + element] - output_reg[i][it + element] * sum[i])); + } + copy_vector(gradInput + i * element_count + it * WARP_SIZE, out); + } + } + } +} + +} // end of anonymous namespace + +template +void dispatch_scaled_masked_softmax_forward( + output_t *dst, + const input_t *src, + const uint8_t *mask, + const input_t scale, + int query_seq_len, + int key_seq_len, + int batches, + int attn_heads, + int pad_batches) +{ + TORCH_INTERNAL_ASSERT(key_seq_len >= 0 && key_seq_len <= 2048 ); + if (key_seq_len == 0) { + return; + } else { + int log2_elements = log2_ceil(key_seq_len); + const int next_power_of_two = 1 << log2_elements; + int batch_count = batches * attn_heads * query_seq_len; + + // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_forward. + int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; + + // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_forward. + int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; + + // use 128 threads per block to maximimize gpu utilization + constexpr int threads_per_block = 128; + + int warps_per_block = (threads_per_block / warp_size); + int batches_per_block = warps_per_block * batches_per_warp; + TORCH_INTERNAL_ASSERT(query_seq_len%batches_per_block == 0); + dim3 blocks(query_seq_len/batches_per_block, attn_heads, batches); + dim3 threads(warp_size, warps_per_block, 1); + // Launch code would be more elegant if C++ supported FOR CONSTEXPR + switch (log2_elements) { + case 0: // 1 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 1: // 2 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 2: // 4 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 3: // 8 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 4: // 16 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 5: // 32 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 6: // 64 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 7: // 128 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 8: // 256 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 9: // 512 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 10: // 1024 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + case 11: // 2048 + scaled_masked_softmax_warp_forward + <<>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches); + break; + default: + break; + } + } +} + +template +void dispatch_scaled_masked_softmax_backward( + output_t *grad_input, + input_t *grad, + const input_t *output, + const acc_t scale, + int query_seq_len, + int key_seq_len, + int batches, + int attn_heads) +{ + TORCH_INTERNAL_ASSERT( key_seq_len >= 0 && key_seq_len <= 2048 ); + if (key_seq_len == 0) { + return; + } else { + int log2_elements = log2_ceil(key_seq_len); + const int next_power_of_two = 1 << log2_elements; + int batch_count = batches * attn_heads * query_seq_len; + + // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. + int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; + + // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. + int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; + + // use 128 threads per block to maximimize gpu utilization + constexpr int threads_per_block = 128; + + int warps_per_block = (threads_per_block / warp_size); + int batches_per_block = warps_per_block * batches_per_warp; + int blocks = batch_count/batches_per_block; + dim3 threads(warp_size, warps_per_block, 1); + // Launch code would be more elegant if C++ supported FOR CONSTEXPR + switch (log2_elements) { + case 0: // 1 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 1: // 2 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 2: // 4 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 3: // 8 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 4: // 16 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 5: // 32 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 6: // 64 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 7: // 128 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 8: // 256 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 9: // 512 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 10: // 1024 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + case 11: // 2048 + scaled_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, key_seq_len); + break; + default: + break; + } + } +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_masked_softmax_cuda.cu b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_masked_softmax_cuda.cu new file mode 100644 index 0000000000000000000000000000000000000000..7e8317c4f48b0419779d2a871b7ccf3deb36ab0d --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_masked_softmax_cuda.cu @@ -0,0 +1,112 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "scaled_masked_softmax.h" +#include "type_shim.h" + +namespace multihead_attn { +namespace fused_softmax { +namespace scaled_masked_softmax { + +torch::Tensor fwd_cuda( + torch::Tensor const& input, + torch::Tensor const& mask, + float scale_factor) +{ + // input is a 4d tensor with dimensions [batches, attn_heads, seq_len, seq_len] + const int batches = input.size(0); + const int pad_batches = mask.size(0); + const int attn_heads = input.size(1); + const int query_seq_len = input.size(2); + const int key_seq_len = input.size(3); + TORCH_INTERNAL_ASSERT(key_seq_len <= 2048); + TORCH_INTERNAL_ASSERT(query_seq_len > 1); + TORCH_INTERNAL_ASSERT(pad_batches == 1 || pad_batches == batches); + TORCH_INTERNAL_ASSERT(mask.size(1) == 1); + TORCH_INTERNAL_ASSERT(mask.size(2) == query_seq_len); + TORCH_INTERNAL_ASSERT(mask.size(3) == key_seq_len); + + // Output + auto act_options = input.options().requires_grad(false); + torch::Tensor softmax_results = + torch::empty({batches, attn_heads, query_seq_len, key_seq_len}, act_options); + + // Softmax Intermediate Result Ptr + void* input_ptr = static_cast(input.data_ptr()); + void* mask_ptr = static_cast(mask.data_ptr()); + void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); + + DISPATCH_HALF_AND_BFLOAT( + input.scalar_type(), + "dispatch_scaled_masked_softmax_forward", + dispatch_scaled_masked_softmax_forward( + reinterpret_cast(softmax_results_ptr), + reinterpret_cast(input_ptr), + reinterpret_cast(mask_ptr), + scale_factor, + query_seq_len, + key_seq_len, + batches, + attn_heads, + pad_batches); + ); + return softmax_results; +} + +torch::Tensor bwd_cuda( + torch::Tensor const& output_grads_, + torch::Tensor const& softmax_results_, + float scale_factor) { + + auto output_grads = output_grads_.contiguous(); + auto softmax_results = softmax_results_.contiguous(); + + //output grads is a 4d tensor with dimensions [batches, attn_heads, seq_len, seq_len] + const int batches = output_grads.size(0); + const int attn_heads = output_grads.size(1); + const int query_seq_len = output_grads.size(2); + const int key_seq_len = output_grads.size(3); + + void* output_grads_ptr = static_cast(output_grads.data_ptr()); + + //Softmax Grad + DISPATCH_HALF_AND_BFLOAT( + output_grads_.scalar_type(), + "dispatch_scaled_masked_softmax_backward", + dispatch_scaled_masked_softmax_backward( + reinterpret_cast(output_grads_ptr), + reinterpret_cast(output_grads_ptr), + reinterpret_cast(softmax_results.data_ptr()), + scale_factor, + query_seq_len, + key_seq_len, + batches, + attn_heads); + ); + + //backward pass is completely in-place + return output_grads; +} +} +} +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_upper_triang_masked_softmax.cpp b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_upper_triang_masked_softmax.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea283588db2d4aef256c2ab25533630170fe416b --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_upper_triang_masked_softmax.cpp @@ -0,0 +1,72 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +namespace multihead_attn { +namespace fused_softmax { +namespace scaled_upper_triang_masked_softmax { + +torch::Tensor fwd_cuda( + torch::Tensor const& input, + float scale_factor); + +torch::Tensor bwd_cuda( + torch::Tensor const& output_grads, + torch::Tensor const& softmax_results, + float scale_factor); + +torch::Tensor fwd(torch::Tensor const& input, float scale_factor) { + AT_ASSERTM(input.dim() == 3, "expected 3D tensor"); + AT_ASSERTM((input.scalar_type() == at::ScalarType::Half) || + (input.scalar_type() == at::ScalarType::BFloat16), + "Only fp16 and bf16 are supported"); + + return fwd_cuda(input, scale_factor); +} + +torch::Tensor bwd( + torch::Tensor const& output_grads, + torch::Tensor const& softmax_results, + float scale_factor) { + + AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); + AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); + + AT_ASSERTM((output_grads.scalar_type() == at::ScalarType::Half) || + (output_grads.scalar_type() == at::ScalarType::BFloat16), + "Only fp16 and bf16 are supported"); + AT_ASSERTM((softmax_results.scalar_type() == at::ScalarType::Half) || + (softmax_results.scalar_type() == at::ScalarType::BFloat16), + "Only fp16 and bf16 are supported"); + + return bwd_cuda(output_grads, softmax_results, scale_factor); +} + +} // end namespace scaled_upper_triang_masked_softmax +} // end namespace fused_softmax +} // end namespace multihead_attn + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward", + &multihead_attn::fused_softmax::scaled_upper_triang_masked_softmax::fwd, + "Self Multihead Attention scaled, time masked softmax -- Forward."); + m.def("backward", + &multihead_attn::fused_softmax::scaled_upper_triang_masked_softmax::bwd, + "Self Multihead Attention scaled, time masked softmax -- Backward."); +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_upper_triang_masked_softmax.h b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_upper_triang_masked_softmax.h new file mode 100644 index 0000000000000000000000000000000000000000..addca0a0a3bbe5322c4e4522471f17a3c00e2ee1 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_upper_triang_masked_softmax.h @@ -0,0 +1,511 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace { + +template +__device__ __inline__ void copy_vector(Datatype *dst, const Datatype *src); + +template <> +__device__ __inline__ void copy_vector(c10::BFloat16 *dst, const c10::BFloat16 *src) { *dst = *src; } + +template <> +__device__ __inline__ void copy_vector(c10::BFloat16 *dst, const c10::BFloat16 *src) { *((float2*) dst) = *((float2*) src); } + +template <> +__device__ __inline__ void copy_vector(c10::Half *dst, const c10::Half *src) { *dst = *src; } + +template <> +__device__ __inline__ void copy_vector(c10::Half *dst, const c10::Half *src) { *((float2*) dst) = *((float2*) src); } + +template <> +__device__ __inline__ void copy_vector(uint8_t *dst, const uint8_t *src) { *dst = *src; } + +template <> +__device__ __inline__ void copy_vector(uint8_t *dst, const uint8_t *src) {*((half2*) dst) = *((half2*) src); } + +template +__device__ __inline__ void copy_zero_vector(Datatype *dst); + +template <> +__device__ __inline__ void copy_zero_vector(c10::BFloat16 *dst) { *dst = 0.0; } + +template <> +__device__ __inline__ void copy_zero_vector(c10::BFloat16 *dst) { *((float2*) dst) = make_float2(0.0f, 0.0f); } + +template <> +__device__ __inline__ void copy_zero_vector(c10::Half *dst) { *dst = 0.0; } + +template <> +__device__ __inline__ void copy_zero_vector(c10::Half *dst) { *((float2*) dst) = make_float2(0.0f, 0.0f); } + + +int log2_ceil(int value) { + int log2_value = 0; + while ((1 << log2_value) < value) ++log2_value; + return log2_value; +} + +template +struct Add { + __device__ __forceinline__ T operator()(T a, T b) const { + return a + b; + } +}; + +template +struct Max { + __device__ __forceinline__ T operator()(T a, T b) const { + return a < b ? b : a; + } +}; + +template +__device__ __forceinline__ T WARP_SHFL_XOR_NATIVE(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if CUDA_VERSION >= 9000 + return __shfl_xor_sync(mask, value, laneMask, width); +#else + return __shfl_xor(value, laneMask, width); +#endif +} + +template class ReduceOp> +__device__ __forceinline__ void warp_reduce(acc_t* sum) { + ReduceOp r; + #pragma unroll + for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + acc_t b = WARP_SHFL_XOR_NATIVE(sum[i], offset, WARP_SIZE); + sum[i] = r(sum[i], b); + } + } +} + +/* + * Extended softmax (from native aten pytorch) with following additional features + * 1) input scaling + * 2) Implicit time (diagonal masking) + */ +template +__global__ void scaled_upper_triang_masked_softmax_warp_forward( + output_t *dst, + const input_t *src, + const acc_t scale, + int micro_batch_size, + int stride, + int element_count) +{ + // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and + // warp_size of method warp_softmax_forward_kernel. + constexpr int next_power_of_two = 1 << log2_elements; + constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; + constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; + constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; + constexpr int ELEMENTS_PER_LDG_STG = 4; + + int first_batch = (blockDim.y * blockIdx.y + threadIdx.y) * gridDim.x * WARP_BATCH + blockIdx.x; + int local_seq = blockIdx.x + 1; + int warp_iteration_limit = (local_seq + ELEMENTS_PER_LDG_STG * WARP_SIZE - 1)/ WARP_SIZE; + + // micro_batch_size might not be a multiple of WARP_BATCH. Check how + // many batches have to computed within this WARP. + int local_batches = micro_batch_size - first_batch; + if (local_batches > WARP_BATCH) + local_batches = WARP_BATCH; + + // there might be multiple batches per warp. compute the index within the batch + int local_idx = threadIdx.x; + + src += first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; + dst += first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; + + // load data from global memory + acc_t elements[WARP_BATCH][WARP_ITERATIONS]; + input_t temp_data[ELEMENTS_PER_LDG_STG]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + int batch_element_count = (i >= local_batches) ? 0 : local_seq; + + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) { + int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; + + if (element_index < batch_element_count) { + copy_vector(temp_data, src + i*element_count*stride + it*WARP_SIZE); + + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + if ((element_index + element) < batch_element_count) { + elements[i][it+element] = (acc_t)temp_data[element] * scale; + } else { + elements[i][it + element] = -std::numeric_limits::infinity(); + } + } + } else { + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + elements[i][it + element] = -std::numeric_limits::infinity(); + } + } + } + } + + // compute max_value + acc_t max_value[WARP_BATCH]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + max_value[i] = elements[i][0]; + #pragma unroll + for (int it = 1; it < WARP_ITERATIONS; ++it) { + max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; + } + } + warp_reduce(max_value); + + acc_t sum[WARP_BATCH] { 0.0f }; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; ++it) { + if (it < warp_iteration_limit) { + elements[i][it] = std::exp((elements[i][it] - max_value[i])); + sum[i] += elements[i][it]; + } + } + } + warp_reduce(sum); + + // store result + output_t out[ELEMENTS_PER_LDG_STG]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + if (i >= local_batches) + break; + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) { + int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; + + if (element_index < local_seq) { + + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + if (element_index + element < local_seq) { + out[element] = elements[i][it + element] / sum[i]; + } else { + out[element] = 0; + } + } + copy_vector(dst + i * element_count * stride + it * WARP_SIZE, out); + } else if (element_index < element_count) { + copy_zero_vector(dst + i * element_count * stride + it * WARP_SIZE); + } else { + break; + } + } + } +} + +template +__global__ void scaled_upper_triang_masked_softmax_warp_backward( + output_t *gradInput, + input_t *grad, + const input_t *output, + acc_t scale, + int micro_batch_size, + int stride, + int element_count) +{ + // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and + // warp_size of method warp_softmax_backward_kernel. + constexpr int next_power_of_two = 1 << log2_elements; + constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; + constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; + constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; + constexpr int ELEMENTS_PER_LDG_STG = 4; + + int first_batch = (blockDim.y * blockIdx.y + threadIdx.y) * gridDim.x * WARP_BATCH + blockIdx.x; + int local_seq = blockIdx.x + 1; + + // micro_batch_size might not be a multiple of WARP_BATCH. Check how + // many batches have to computed within this WARP. + int local_batches = micro_batch_size - first_batch; + if (local_batches > WARP_BATCH) + local_batches = WARP_BATCH; + + // there might be multiple batches per warp. compute the index within the batch + int local_idx = threadIdx.x; + + // the first element to process by the current thread + int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; + grad += thread_offset; + output += thread_offset; + gradInput += thread_offset; + + // load data from global memory + acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] { 0.0f }; + acc_t output_reg[WARP_BATCH][WARP_ITERATIONS] { 0.0f }; + input_t temp_grad[ELEMENTS_PER_LDG_STG]; + input_t temp_output[ELEMENTS_PER_LDG_STG]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + int batch_element_count = (i >= local_batches) ? 0 : local_seq; + + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) { + int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; + if (element_index < batch_element_count) { + copy_vector(temp_grad, grad + i * element_count * stride + it * WARP_SIZE); + copy_vector(temp_output, output + i * element_count * stride + it * WARP_SIZE); + + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + if (element_index + element < batch_element_count) { + output_reg[i][it + element] = (acc_t)temp_output[element]; + } + } + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + if (element_index + element < batch_element_count) { + grad_reg[i][it + element] = (acc_t)temp_grad[element] * output_reg[i][it + element]; + } + } + } + } + } + + acc_t sum[WARP_BATCH]; + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + sum[i] = grad_reg[i][0]; + #pragma unroll + for (int it = 1; it < WARP_ITERATIONS; ++it) { + sum[i] += grad_reg[i][it]; + } + } + warp_reduce(sum); + + // store result + #pragma unroll + for (int i = 0; i < WARP_BATCH; ++i) { + if (i >= local_batches) + break; + #pragma unroll + for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) { + int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; + if (element_index < element_count) { + // compute gradients + output_t out[ELEMENTS_PER_LDG_STG]; + #pragma unroll + for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) { + out[element] = (output_t)(scale * (grad_reg[i][it + element] - output_reg[i][it + element] * sum[i])); + } + copy_vector(gradInput + i * element_count * stride + it * WARP_SIZE, out); + } + } + } +} + +} // end of anonymous namespace + +template +void dispatch_scaled_upper_triang_masked_softmax_forward( + output_t *dst, + const input_t *src, + const input_t scale, + int softmax_elements, + int softmax_elements_stride, + int attn_batches) +{ + TORCH_INTERNAL_ASSERT(softmax_elements >= 0 && softmax_elements <= 2048 ); + if (softmax_elements == 0) { + return; + } else { + int log2_elements = log2_ceil(softmax_elements); + const int next_power_of_two = 1 << log2_elements; + int seq_len = softmax_elements; + int batch_count = attn_batches * seq_len; + + // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_forward. + int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; + + // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_forward. + int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; + + // use 128 threads per block to maximimize gpu utilization + constexpr int threads_per_block = 128; + + int warps_per_block = (threads_per_block / warp_size); + int batches_per_block = warps_per_block * batches_per_warp; + TORCH_INTERNAL_ASSERT(attn_batches % batches_per_block == 0); + int blocks_per_seq = attn_batches / batches_per_block; + dim3 blocks(seq_len, blocks_per_seq, 1); + dim3 threads(warp_size, warps_per_block, 1); + // Launch code would be more elegant if C++ supported FOR CONSTEXPR + switch (log2_elements) { + case 0: // 1 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 1: // 2 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 2: // 4 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 3: // 8 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 4: // 16 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 5: // 32 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 6: // 64 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 7: // 128 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 8: // 256 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 9: // 512 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 10: // 1024 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 11: // 2048 + scaled_upper_triang_masked_softmax_warp_forward + <<>>(dst, src, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + default: + break; + } + } +} + +template +void dispatch_scaled_upper_triang_masked_softmax_backward( + output_t *grad_input, + input_t *grad, + const input_t *output, + const acc_t scale, + int softmax_elements, + int softmax_elements_stride, + int attn_batches) +{ + TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 2048 ); + if (softmax_elements == 0) { + return; + } else { + int log2_elements = log2_ceil(softmax_elements); + const int next_power_of_two = 1 << log2_elements; + int seq_len = softmax_elements; + int batch_count = attn_batches * seq_len; + + // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. + int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; + + // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. + int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; + + // use 128 threads per block to maximimize gpu utilization + constexpr int threads_per_block = 128; + + int warps_per_block = (threads_per_block / warp_size); + int batches_per_block = warps_per_block * batches_per_warp; + TORCH_INTERNAL_ASSERT(attn_batches % batches_per_block == 0); + int blocks_per_seq = attn_batches / batches_per_block; + dim3 blocks(seq_len, blocks_per_seq, 1); + dim3 threads(warp_size, warps_per_block, 1); + // Launch code would be more elegant if C++ supported FOR CONSTEXPR + switch (log2_elements) { + case 0: // 1 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 1: // 2 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 2: // 4 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 3: // 8 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 4: // 16 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 5: // 32 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 6: // 64 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 7: // 128 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 8: // 256 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 9: // 512 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 10: // 1024 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + case 11: // 2048 + scaled_upper_triang_masked_softmax_warp_backward + <<>>(grad_input, grad, output, scale, batch_count, softmax_elements_stride, softmax_elements); + break; + default: + break; + } + } +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_upper_triang_masked_softmax_cuda.cu b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_upper_triang_masked_softmax_cuda.cu new file mode 100644 index 0000000000000000000000000000000000000000..5efc3d41280cf7b4f2fdf6afbe1271ffbe21037c --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/scaled_upper_triang_masked_softmax_cuda.cu @@ -0,0 +1,98 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "scaled_upper_triang_masked_softmax.h" +#include "type_shim.h" + +namespace multihead_attn { +namespace fused_softmax { +namespace scaled_upper_triang_masked_softmax { + +torch::Tensor fwd_cuda( + torch::Tensor const& input, + float scale_factor) +{ + // input is a 3d tensor with dimensions [attn_batches, seq_len, seq_len] + const int attn_batches = input.size(0); + const int seq_len = input.size(1); + TORCH_INTERNAL_ASSERT(seq_len <= 2048); + + // Output + auto act_options = input.options().requires_grad(false); + torch::Tensor softmax_results = + torch::empty({attn_batches, seq_len, seq_len}, act_options); + + // Softmax Intermediate Result Ptr + void* input_ptr = static_cast(input.data_ptr()); + void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); + + DISPATCH_HALF_AND_BFLOAT( + input.scalar_type(), + "dispatch_scaled_upper_triang_masked_softmax_forward", + dispatch_scaled_upper_triang_masked_softmax_forward( + reinterpret_cast(softmax_results_ptr), + reinterpret_cast(input_ptr), + scale_factor, + seq_len, + seq_len, + attn_batches); + ); + return softmax_results; +} + + +torch::Tensor bwd_cuda( + torch::Tensor const& output_grads_, + torch::Tensor const& softmax_results_, + float scale_factor) { + + auto output_grads = output_grads_.contiguous(); + auto softmax_results = softmax_results_.contiguous(); + + //output grads is a 3d tensor with dimensions [attn_batches, seq_len, seq_len] + const int attn_batches = output_grads.size(0); + const int seq_len = output_grads.size(1); + TORCH_INTERNAL_ASSERT(output_grads.size(1) == output_grads.size(2)); + + void* output_grads_ptr = static_cast(output_grads.data_ptr()); + + //Softmax Grad + DISPATCH_HALF_AND_BFLOAT( + output_grads_.scalar_type(), + "dispatch_scaled_upper_triang_masked_softmax_backward", + dispatch_scaled_upper_triang_masked_softmax_backward( + reinterpret_cast(output_grads_ptr), + reinterpret_cast(output_grads_ptr), + reinterpret_cast(softmax_results.data_ptr()), + scale_factor, + seq_len, + seq_len, + attn_batches); + ); + + //backward pass is completely in-place + return output_grads; +} +} +} +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/type_shim.h b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/type_shim.h new file mode 100644 index 0000000000000000000000000000000000000000..6437dcc7c7456beb17fcfc065ef4925abdc3fe23 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/fused_kernels/type_shim.h @@ -0,0 +1,91 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include "compat.h" + + +#define DISPATCH_HALF_AND_BFLOAT(TYPE, NAME, ...) \ + switch(TYPE) \ + { \ + case at::ScalarType::Half: \ + { \ + using scalar_t = at::Half; \ + __VA_ARGS__; \ + break; \ + } \ + case at::ScalarType::BFloat16: \ + { \ + using scalar_t = at::BFloat16; \ + __VA_ARGS__; \ + break; \ + } \ + default: \ + AT_ERROR(#NAME, " not implemented for '", toString(TYPE), "'"); \ + } + + + +#define DISPATCH_FLOAT_HALF_AND_BFLOAT_INOUT_TYPES(TYPEIN, TYPEOUT, NAME, ...) \ + switch(TYPEIN) \ + { \ + case at::ScalarType::Float: \ + { \ + using scalar_t_in = float; \ + switch(TYPEOUT) \ + { \ + case at::ScalarType::Float: \ + { \ + using scalar_t_out = float; \ + __VA_ARGS__; \ + break; \ + } \ + case at::ScalarType::Half: \ + { \ + using scalar_t_out = at::Half; \ + __VA_ARGS__; \ + break; \ + } \ + case at::ScalarType::BFloat16: \ + { \ + using scalar_t_out = at::BFloat16; \ + __VA_ARGS__; \ + break; \ + } \ + default: \ + AT_ERROR(#NAME, " not implemented for '", toString(TYPEOUT), "'"); \ + } \ + break; \ + } \ + case at::ScalarType::Half: \ + { \ + using scalar_t_in = at::Half; \ + using scalar_t_out = at::Half; \ + __VA_ARGS__; \ + break; \ + } \ + case at::ScalarType::BFloat16: \ + { \ + using scalar_t_in = at::BFloat16; \ + using scalar_t_out = at::BFloat16; \ + __VA_ARGS__; \ + break; \ + } \ + default: \ + AT_ERROR(#NAME, " not implemented for '", toString(TYPEIN), "'"); \ + } + diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/distributed.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..53d33622311ef7b43945db40f90f5bf51e07af44 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/distributed.py @@ -0,0 +1,218 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from abc import ABC +from abc import abstractmethod + +import torch +from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors + +from megatron import get_args +from megatron import mpu +from .module import MegatronModule + + + +class MemoryBuffer: + + def __init__(self, numel, dtype): + self.numel = numel + self.dtype = dtype + self.data = torch.zeros(self.numel, + dtype=self.dtype, + device=torch.cuda.current_device(), + requires_grad=False) + + + def zero(self): + """Reset the buffer to zero.""" + self.data.zero_() + + + def get(self, shape, start_index): + """Return a tensor with the input `shape` as a view into the + 1-D data starting at `start_index`.""" + end_index = start_index + shape.numel() + assert end_index <= self.numel, \ + 'requested tensor is out of the buffer range.' + buffer_tensor = self.data[start_index:end_index] + buffer_tensor = buffer_tensor.view(shape) + return buffer_tensor + + + +class DistributedDataParallelBase(MegatronModule, ABC): + """Abstract class for DDP.""" + + def __init__(self, module): + super(DistributedDataParallelBase, self).__init__() + # Keep a pointer to the model. + self.module = module + + + @abstractmethod + def allreduce_gradients(self): + pass + + + def forward(self, *inputs, **kwargs): + return self.module(*inputs, **kwargs) + + + def state_dict(self, destination=None, prefix='', keep_vars=False): + return self.module.state_dict(destination, prefix, keep_vars) + + + def state_dict_for_save_checkpoint(self, destination=None, prefix='', + keep_vars=False): + return self.module.state_dict_for_save_checkpoint(destination, prefix, + keep_vars) + + + def load_state_dict(self, state_dict, strict=True): + self.module.load_state_dict(state_dict, strict=strict) + + + +class DistributedDataParallel(DistributedDataParallelBase): + """DDP with contiguous buffers options to storre and accumulate gradients. + This class: + - has the potential to reduce memory fragmentation. + - provides the option to do the gradient accumulation + in a type other than the params type (for example fp32) + + Arguments: + module: input model. + accumulate_allreduce_grads_in_fp32: if true do the gradient accumulation + and the gradient all-reduce all in in float32. If this option is + true, we require `use_contiguous_buffers` to be true too. + use_contiguous_buffers: if true, use a contiguous buffer to store the + gradients. + """ + + def __init__(self, module, + accumulate_allreduce_grads_in_fp32, + use_contiguous_buffers): + + super(DistributedDataParallel, self).__init__(module) + + self.accumulate_allreduce_grads_in_fp32 \ + = accumulate_allreduce_grads_in_fp32 + self.use_contiguous_buffers = use_contiguous_buffers + # If we are using fp32-accumulate-allreduce explicitly + # this means we need main grads in a continous buffer. + if self.accumulate_allreduce_grads_in_fp32: + assert self.use_contiguous_buffers + + # =================================== + # Rest of this part applies only to + # the case we use continuous buffers. + # =================================== + self._grad_buffers = None + if self.use_contiguous_buffers: + self._grad_buffers = {} + + # Simple function to define buffer type. + def _get_buffer_type(param): + return torch.float if \ + self.accumulate_allreduce_grads_in_fp32 else param.dtype + + # First calculate total number of elements per type. + type_num_elements = {} + for param in self.module.parameters(): + if param.requires_grad: + dtype = _get_buffer_type(param) + type_num_elements[dtype] = type_num_elements.get(dtype, 0) \ + + param.data.nelement() + + # Allocate the buffer. + for dtype, num_elements in type_num_elements.items(): + self._grad_buffers[dtype] = MemoryBuffer(num_elements, dtype) + + # Assume the back prop order is reverse the params order, + # store the start index for the gradients. + for param in self.module.parameters(): + if param.requires_grad: + dtype = _get_buffer_type(param) + type_num_elements[dtype] -= param.data.nelement() + param.main_grad = self._grad_buffers[dtype].get( + param.data.shape, type_num_elements[dtype]) + + # Backward hook. + # Accumalation function for the gradients. We need + # to store them so they don't go out of scope. + self.grad_accs = [] + # Loop over all the parameters in the model. + for param in self.module.parameters(): + if param.requires_grad: + # Expand so we get access to grad_fn. + param_tmp = param.expand_as(param) + # Get the gradient accumulator functtion. + grad_acc = param_tmp.grad_fn.next_functions[0][0] + grad_acc.register_hook(self._make_param_hook(param)) + self.grad_accs.append(grad_acc) + + + def _make_param_hook(self, param): + """Create the all-reduce hook for backprop.""" + # Hook used for back-prop. + def param_hook(*unused): + # Add the gradient to the buffer. + if param.grad.data is not None: + param.main_grad.add_(param.grad.data) + # Now we can deallocate grad memory. + param.grad = None + return param_hook + + + def zero_grad_buffer(self): + """Set the grad buffer data to zero. Needs to be called at the + begining of each iteration.""" + assert self._grad_buffers is not None, 'buffers are not initialized.' + for _, buffer_ in self._grad_buffers.items(): + buffer_.zero() + + + def allreduce_gradients(self): + """Reduce gradients across data parallel ranks.""" + # If we have buffers, simply reduce the data in the buffer. + if self._grad_buffers is not None: + for _, buffer_ in self._grad_buffers.items(): + buffer_.data /= mpu.get_data_parallel_world_size() + torch.distributed.all_reduce( + buffer_.data, group=mpu.get_data_parallel_group()) + else: + # Otherwise, bucketize and all-reduce + buckets = {} + # Pack the buckets. + for param in self.module.parameters(): + if param.requires_grad and param.grad is not None: + tp = param.data.type() + if tp not in buckets: + buckets[tp] = [] + buckets[tp].append(param) + param.main_grad = param.grad + + # For each bucket, all-reduce and copy all-reduced grads. + for tp in buckets: + bucket = buckets[tp] + grads = [param.grad.data for param in bucket] + coalesced = _flatten_dense_tensors(grads) + coalesced /= mpu.get_data_parallel_world_size() + torch.distributed.all_reduce( + coalesced, group=mpu.get_data_parallel_group()) + for buf, synced in zip(grads, _unflatten_dense_tensors( + coalesced, grads)): + buf.copy_(synced) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/enums.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..b6992fefafeda2fc15be0f61c08924385a7c0933 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/enums.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import enum + +class LayerType(enum.Enum): + encoder = 1 + decoder = 2 + +class AttnType(enum.Enum): + self_attn = 1 + cross_attn = 2 + +class AttnMaskType(enum.Enum): + padding = 1 + causal = 2 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/fused_softmax.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/fused_softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..097b29ef4c64d2eedf79d50bde679bc4f3e9c3d2 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/fused_softmax.py @@ -0,0 +1,164 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from megatron.model.enums import AttnMaskType + + +class ScaledUpperTriangMaskedSoftmax(torch.autograd.Function): + """ + Fused operation which performs following three operations in sequence + 1. Scale the tensor. + 2. Apply upper triangular mask (typically used in gpt models). + 3. Perform softmax. + """ + + @staticmethod + def forward(ctx, inputs, scale): + import scaled_upper_triang_masked_softmax_cuda + + scale_t = torch.tensor([scale]) + + softmax_results = scaled_upper_triang_masked_softmax_cuda.forward( + inputs, scale_t[0] + ) + ctx.save_for_backward(softmax_results, scale_t) + return softmax_results + + @staticmethod + def backward(ctx, output_grads): + import scaled_upper_triang_masked_softmax_cuda + + softmax_results, scale_t = ctx.saved_tensors + + input_grads = scaled_upper_triang_masked_softmax_cuda.backward( + output_grads, softmax_results, scale_t[0] + ) + return input_grads, None + + +class ScaledMaskedSoftmax(torch.autograd.Function): + """ + Fused operation which performs following three operations in sequence + 1. Scale the tensor. + 2. Apply the mask. + 3. Perform softmax. + """ + + @staticmethod + def forward(ctx, inputs, mask, scale): + import scaled_masked_softmax_cuda + + scale_t = torch.tensor([scale]) + + softmax_results = scaled_masked_softmax_cuda.forward( + inputs, mask, scale_t[0] + ) + ctx.save_for_backward(softmax_results, scale_t) + return softmax_results + + @staticmethod + def backward(ctx, output_grads): + import scaled_masked_softmax_cuda + + softmax_results, scale_t = ctx.saved_tensors + + input_grads = scaled_masked_softmax_cuda.backward( + output_grads, softmax_results, scale_t[0] + ) + return input_grads, None, None + + +class FusedScaleMaskSoftmax(torch.nn.Module): + """ + fused operation: scaling + mask + softmax + Arguments: + input_in_fp16: flag to indicate if input in fp16 data format. + attn_mask_type: attention mask type (pad or causal) + mask_func: mask function to be applied. + softmax_in_fp32: if true, softmax in performed at fp32 precision. + scale: scaling factor used in input tensor scaling. + + """ + + def __init__( + self, + input_in_fp16, + input_in_bf16, + attn_mask_type, + scaled_masked_softmax_fusion, + mask_func, + softmax_in_fp32, + scale, + ): + super(FusedScaleMaskSoftmax, self).__init__() + self.input_in_fp16 = input_in_fp16 + self.input_in_bf16 = input_in_bf16 + assert not (self.input_in_fp16 and self.input_in_bf16),\ + 'both fp16 and bf16 flags cannot be active at the same time.' + self.input_in_float16 = self.input_in_fp16 or self.input_in_bf16 + self.attn_mask_type = attn_mask_type + self.scaled_masked_softmax_fusion = scaled_masked_softmax_fusion + self.mask_func = mask_func + self.softmax_in_fp32 = softmax_in_fp32 + self.scale = scale + + assert ( + self.scale is None or softmax_in_fp32 + ), "softmax should be in fp32 when scaled" + + def forward(self, input, mask): + # [b, np, sq, sk] + assert input.dim() == 4 + data_size = input.size() + query_seq_len = data_size[-2] + key_seq_len = data_size[-1] + attn_batch_size = data_size[0] * data_size[1] + + # constraints on various tensor dimensions to enable warp based + # optimization and upper triangular optimization (for causal mask) + custom_kernel_constraint = key_seq_len > 16 and key_seq_len <= 2048 and \ + query_seq_len % 4 == 0 and attn_batch_size % 4 == 0 + + # invoke custom kernel + if self.input_in_float16 and mask is not None and \ + custom_kernel_constraint and self.scaled_masked_softmax_fusion: + scale = self.scale if self.scale is not None else 1.0 + + if self.attn_mask_type == AttnMaskType.causal: + assert query_seq_len == key_seq_len, \ + "causal mask is only for self attention" + input = input.view(-1, query_seq_len, key_seq_len) + probs = ScaledUpperTriangMaskedSoftmax.apply(input, scale) + probs = probs.view(*data_size) + else: + assert self.attn_mask_type == AttnMaskType.padding + probs = ScaledMaskedSoftmax.apply(input, mask, scale) + else: + if self.input_in_float16 and self.softmax_in_fp32: + input = input.float() + + if self.scale is not None: + input = input * self.scale + mask_output = self.mask_func(input, mask) if mask is not None else input + probs = torch.nn.Softmax(dim=-1)(mask_output) + + if self.input_in_float16 and self.softmax_in_fp32: + if self.input_in_fp16: + probs = probs.half() + else: + probs = probs.bfloat16() + + return probs diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/module.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/module.py new file mode 100644 index 0000000000000000000000000000000000000000..df92d95a9fd040166cacd3b9b21af18a1e0a8b7b --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/module.py @@ -0,0 +1,189 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Megatron Module""" + +import torch +from torch.autograd import Variable +from torch.nn.parameter import Parameter + +from megatron import get_args +from megatron import mpu + + +_FLOAT_TYPES = (torch.FloatTensor, torch.cuda.FloatTensor) +_HALF_TYPES = (torch.HalfTensor, torch.cuda.HalfTensor) +_BF16_TYPES = (torch.BFloat16Tensor, torch.cuda.BFloat16Tensor) + + + +def param_is_not_shared(param): + return not hasattr(param, 'shared') or not param.shared + + + +class MegatronModule(torch.nn.Module): + """Megatron specific extensions of torch Module with support + for pipelining.""" + + def __init__(self, share_word_embeddings=True): + super(MegatronModule, self).__init__() + self.share_word_embeddings = share_word_embeddings + + + def state_dict_for_save_checkpoint(self, destination=None, prefix='', + keep_vars=False): + """Use this function to override the state dict for + saving checkpoints.""" + return self.state_dict(destination, prefix, keep_vars) + + + def word_embeddings_weight(self): + if mpu.is_pipeline_first_stage(ignore_virtual=True): + return self.language_model.embedding.word_embeddings.weight + if mpu.is_pipeline_last_stage(ignore_virtual=True): + if not self.share_word_embeddings: + raise Exception('word_embeddings_weight() called for last ' + 'stage, but share_word_embeddings is false') + return self.word_embeddings.weight + raise Exception('word_embeddings_weight() should be ' + 'called for first and last stage only') + + + def initialize_word_embeddings(self, init_method_normal): + args = get_args() + if not self.share_word_embeddings: + raise Exception('initialize_word_embeddings() was called but ' + 'share_word_embeddings is false') + + # This function just initializes the word embeddings in the final stage + # when we are using pipeline parallelism. If we aren't using pipeline + # parallelism there is nothing to do. + if args.pipeline_model_parallel_size == 1: + return + + # Parameters are shared between the word embeddings layer, and the + # heads at the end of the model. In a pipelined setup with more than + # one stage, the initial embedding layer and the head are on different + # workers, so we do the following: + # 1. Create a second copy of word_embeddings on the last stage, with + # initial parameters of 0.0. + # 2. Do an all-reduce between the first and last stage to ensure that + # the two copies of word_embeddings start off with the same + # parameter values. + # 3. In the training loop, before an all-reduce between the grads of + # the two word_embeddings layers to ensure that every applied weight + # update is the same on both stages. + if mpu.is_pipeline_last_stage(): + assert not mpu.is_pipeline_first_stage() + self._word_embeddings_for_head_key = 'word_embeddings_for_head' + # set word_embeddings weights to 0 here, then copy first + # stage's weights using all_reduce below. + self.word_embeddings = mpu.VocabParallelEmbedding( + args.padded_vocab_size, args.hidden_size, + init_method=init_method_normal(args.init_method_std)) + self.word_embeddings.weight.data.fill_(0) + self.word_embeddings.weight.shared = True + + # Ensure that first and last stages have the same initial parameter + # values. + if torch.distributed.is_initialized(): + if mpu.is_pipeline_first_stage() or mpu.is_pipeline_last_stage(): + torch.distributed.all_reduce(self.word_embeddings_weight().data, + group=mpu.get_embedding_group()) + else: + print("WARNING! Distributed processes aren't initialized, so " + "word embeddings in the last layer are not initialized. " + "If you are just manipulating a model this is fine, but " + "this needs to be handled manually. If you are training " + "something is definitely wrong.") + + +def conversion_helper(val, conversion): + """Apply conversion to val. Recursively apply conversion if `val` + #is a nested tuple/list structure.""" + if not isinstance(val, (tuple, list)): + return conversion(val) + rtn = [conversion_helper(v, conversion) for v in val] + if isinstance(val, tuple): + rtn = tuple(rtn) + return rtn + + +def fp32_to_float16(val, float16_convertor): + """Convert fp32 `val` to fp16/bf16""" + def half_conversion(val): + val_typecheck = val + if isinstance(val_typecheck, (Parameter, Variable)): + val_typecheck = val.data + if isinstance(val_typecheck, _FLOAT_TYPES): + val = float16_convertor(val) + return val + return conversion_helper(val, half_conversion) + + +def float16_to_fp32(val): + """Convert fp16/bf16 `val` to fp32""" + def float_conversion(val): + val_typecheck = val + if isinstance(val_typecheck, (Parameter, Variable)): + val_typecheck = val.data + if isinstance(val_typecheck, (_BF16_TYPES, _HALF_TYPES)): + val = val.float() + return val + return conversion_helper(val, float_conversion) + + + +class Float16Module(MegatronModule): + + def __init__(self, module, args): + super(Float16Module, self).__init__() + + if args.fp16: + self.add_module('module', module.half()) + def float16_convertor(val): + return val.half() + elif args.bf16: + self.add_module('module', module.bfloat16()) + def float16_convertor(val): + return val.bfloat16() + else: + raise Exception('should not be here') + + self.float16_convertor = float16_convertor + + + def forward(self, *inputs, **kwargs): + if mpu.is_pipeline_first_stage(): + inputs = fp32_to_float16(inputs, self.float16_convertor) + outputs = self.module(*inputs, **kwargs) + if mpu.is_pipeline_last_stage(): + outputs = float16_to_fp32(outputs) + return outputs + + + def state_dict(self, destination=None, prefix='', keep_vars=False): + return self.module.state_dict(destination, prefix, keep_vars) + + + def state_dict_for_save_checkpoint(self, destination=None, prefix='', + keep_vars=False): + return self.module.state_dict_for_save_checkpoint(destination, prefix, + keep_vars) + + + def load_state_dict(self, state_dict, strict=True): + self.module.load_state_dict(state_dict, strict=strict) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/multiple_choice.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/multiple_choice.py new file mode 100644 index 0000000000000000000000000000000000000000..c43bd969c0ded670e3eb794a8e630e36e7409eee --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/multiple_choice.py @@ -0,0 +1,130 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Multiple choice model.""" + +import torch + +from megatron import get_args, print_rank_last +from megatron import mpu +from megatron.model.enums import AttnMaskType +from megatron.model.bert_model import bert_extended_attention_mask, bert_position_ids +from megatron.model.language_model import get_language_model +from megatron.model.utils import get_linear_layer +from megatron.model.utils import init_method_normal +from megatron.model.utils import scaled_init_method_normal +from .module import MegatronModule + + +class MultipleChoice(MegatronModule): + + def __init__(self, + num_tokentypes=2, + pre_process=True, + post_process=True): + super(MultipleChoice, self).__init__(share_word_embeddings=False) + args = get_args() + + init_method = init_method_normal(args.init_method_std) + self.pre_process = pre_process + self.post_process = post_process + + self.language_model, self._language_model_key = get_language_model( + num_tokentypes=num_tokentypes, + add_pooler=True, + encoder_attn_mask_type=AttnMaskType.padding, + init_method=init_method, + scaled_init_method=scaled_init_method_normal(args.init_method_std, + args.num_layers), + pre_process=self.pre_process, + post_process=self.post_process) + + # Multi-choice head. + if self.post_process: + self.multichoice_dropout = torch.nn.Dropout(args.hidden_dropout) + self.multichoice_head = get_linear_layer(args.hidden_size, 1, + init_method) + self._multichoice_head_key = 'multichoice_head' + + def set_input_tensor(self, input_tensor): + """See megatron.model.transformer.set_input_tensor()""" + self.language_model.set_input_tensor(input_tensor) + + def forward(self, model_input, attention_mask, tokentype_ids=None): + + # [batch, choices, sequence] --> [batch * choices, sequence] --> + # transformer --> [batch, choices] --> softmax + + # Ensure the shape is [batch-size, choices, sequence] + assert len(attention_mask.shape) == 3 + num_choices = attention_mask.shape[1] + + # Reshape and treat choice dimension the same as batch. + attention_mask = attention_mask.view(-1, attention_mask.size(-1)) + extended_attention_mask = bert_extended_attention_mask(attention_mask) + + input_ids = model_input + # Do the same as attention_mask for input_ids, tokentype_ids + assert len(input_ids.shape) == 3 + assert len(tokentype_ids.shape) == 3 + input_ids = input_ids.view(-1, input_ids.size(-1)) + tokentype_ids = tokentype_ids.view(-1, tokentype_ids.size(-1)) + position_ids = bert_position_ids(input_ids) + + lm_output = self.language_model( + input_ids, + position_ids, + extended_attention_mask, + tokentype_ids=tokentype_ids + ) + if self.post_process: + _, pooled_output = lm_output + multichoice_output = self.multichoice_dropout(pooled_output) + multichoice_logits = self.multichoice_head(multichoice_output) + + # Reshape back to separate choices. + multichoice_logits = multichoice_logits.view(-1, num_choices) + + return multichoice_logits + return lm_output + + def state_dict_for_save_checkpoint(self, destination=None, prefix='', + keep_vars=False): + """For easy load when model is combined with other heads, + add an extra key.""" + + state_dict_ = {} + state_dict_[self._language_model_key] \ + = self.language_model.state_dict_for_save_checkpoint( + destination, prefix, keep_vars) + if self.post_process: + state_dict_[self._multichoice_head_key] \ + = self.multichoice_head.state_dict( + destination, prefix, keep_vars) + return state_dict_ + + def load_state_dict(self, state_dict, strict=True): + """Customized load.""" + + self.language_model.load_state_dict( + state_dict[self._language_model_key], strict=strict) + if self.post_process: + if self._multichoice_head_key in state_dict: + self.multichoice_head.load_state_dict( + state_dict[self._multichoice_head_key], strict=strict) + else: + print_rank_last('***WARNING*** could not find {} in the checkpoint, ' + 'initializing to random'.format( + self._multichoice_head_key)) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/t5_model.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/t5_model.py new file mode 100644 index 0000000000000000000000000000000000000000..beb4f0ee5a7fe49e8f8ab6df84e7087fd27c99dc --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/model/t5_model.py @@ -0,0 +1,174 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""T5 model.""" + +import torch + +from megatron import ( + get_args, + mpu +) +from megatron.model.enums import AttnMaskType +from megatron.model.language_model import parallel_lm_logits, get_language_model +from megatron.model.transformer import LayerNorm +from megatron.model.utils import ( + openai_gelu, + get_linear_layer, + init_method_normal, + scaled_init_method_normal +) +from .module import MegatronModule + + +def t5_extended_attention_mask(attention_mask_list): + + def attn_mask_postprocess(attn_mask): + # [b, 1, s, s] + extended_attention_mask = attn_mask.unsqueeze(1) + return extended_attention_mask + + return [attn_mask_postprocess(attn_mask) for attn_mask in attention_mask_list] + + +def t5_position_ids(token_ids): + # Create position ids + seq_length = token_ids.size(1) + position_ids = torch.arange(seq_length, dtype=torch.long, + device=token_ids.device) + position_ids = position_ids.unsqueeze(0).expand_as(token_ids) + + return position_ids + + +class T5LMHead(MegatronModule): + """Masked LM head for T5 + + Arguments: + mpu_vocab_size: model parallel size of vocabulary. + hidden_size: hidden size + init_method: init method for weight initialization + layernorm_epsilon: tolerance for layer norm divisions + parallel_output: wether output logits being distributed or not. + """ + + def __init__(self, mpu_vocab_size, parallel_output): + super(T5LMHead, self).__init__() + + args = get_args() + + self.bias = torch.nn.Parameter(torch.zeros(mpu_vocab_size)) + self.bias.model_parallel = True + self.bias.partition_dim = 0 + self.bias.stride = 1 + self.parallel_output = parallel_output + + def forward(self, hidden_states, word_embeddings_weight): + output = parallel_lm_logits(hidden_states, + word_embeddings_weight, + self.parallel_output, + bias=self.bias) + return output + + +class T5Model(MegatronModule): + """T5 Language model.""" + + def __init__(self, num_tokentypes=0, parallel_output=True): + super(T5Model, self).__init__() + args = get_args() + + self.fp16_lm_cross_entropy = args.fp16_lm_cross_entropy + self.parallel_output = parallel_output + init_method = init_method_normal(args.init_method_std) + scaled_init_method = scaled_init_method_normal(args.init_method_std, + args.num_layers) + + self.language_model, self._language_model_key = get_language_model( + num_tokentypes=num_tokentypes, + add_pooler=False, + add_decoder=True, + encoder_attn_mask_type=AttnMaskType.padding, + init_method=init_method, + scaled_init_method=scaled_init_method) + + self.lm_head = T5LMHead( + self.language_model.embedding.word_embeddings.weight.size(0), + parallel_output) + self._lm_head_key = 'lm_head' + + def set_input_tensor(self, input_tensor): + """See megatron.model.transformer.set_input_tensor()""" + self.language_model.set_input_tensor(input_tensor) + + def forward(self, encoder_input_ids, decoder_input_ids, encoder_attn_mask, + decoder_attn_mask, encoder_decoder_attn_mask, + tokentype_ids=None, lm_labels=None, enc_hidden_states=None): + + # Converting the attention masks to proper parameter settings + encoder_attn_mask, decoder_attn_mask, encoder_decoder_attn_mask = t5_extended_attention_mask( + [encoder_attn_mask, decoder_attn_mask, encoder_decoder_attn_mask]) + + encoder_position_ids = t5_position_ids(encoder_input_ids) + decoder_position_ids = t5_position_ids(decoder_input_ids) + + lm_output = self.language_model(encoder_input_ids, + encoder_position_ids, + encoder_attn_mask, + decoder_input_ids, + decoder_position_ids, + decoder_attn_mask, + encoder_decoder_attn_mask, + tokentype_ids=tokentype_ids, + enc_hidden_states=enc_hidden_states) + + decoder_output, encoder_output = lm_output + + # Output. + lm_logits = self.lm_head(decoder_output, + self.language_model.embedding.word_embeddings.weight) + + if lm_labels is None: + return lm_logits, encoder_output + else: + if self.fp16_lm_cross_entropy: + assert lm_logits.dtype == torch.half + lm_loss = mpu.vocab_parallel_cross_entropy(lm_logits, lm_labels) + else: + lm_loss = mpu.vocab_parallel_cross_entropy(lm_logits.float(), + lm_labels) + return lm_loss, encoder_output + + def state_dict_for_save_checkpoint(self, destination=None, prefix='', + keep_vars=False): + """For easy load when model is combined with other heads, + add an extra key.""" + + state_dict_ = {} + state_dict_[self._language_model_key] \ + = self.language_model.state_dict_for_save_checkpoint( + destination, prefix, keep_vars) + state_dict_[self._lm_head_key] \ + = self.lm_head.state_dict_for_save_checkpoint( + destination, prefix, keep_vars) + return state_dict_ + + def load_state_dict(self, state_dict, strict=True): + """Customized load.""" + + self.language_model.load_state_dict( + state_dict[self._language_model_key], strict=strict) + self.lm_head.load_state_dict(state_dict[self._lm_head_key], + strict=strict) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/__init__.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2686de71fdd0c886690ef96a6ad319cd30eae34c --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/__init__.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Model parallel utility interface.""" + +from .cross_entropy import vocab_parallel_cross_entropy + +from .data import broadcast_data + +from .initialize import is_unitialized +from .initialize import destroy_model_parallel +from .initialize import get_data_parallel_group +from .initialize import get_data_parallel_rank +from .initialize import get_data_parallel_world_size +from .initialize import get_embedding_group +from .initialize import get_model_parallel_group +from .initialize import get_tensor_model_parallel_group +from .initialize import get_pipeline_model_parallel_group +from .initialize import get_tensor_model_parallel_rank, set_tensor_model_parallel_rank +from .initialize import get_pipeline_model_parallel_rank, set_pipeline_model_parallel_rank +from .initialize import is_pipeline_first_stage, is_pipeline_last_stage +from .initialize import get_tensor_model_parallel_src_rank +from .initialize import get_pipeline_model_parallel_first_rank +from .initialize import get_pipeline_model_parallel_last_rank +from .initialize import get_pipeline_model_parallel_next_rank +from .initialize import get_pipeline_model_parallel_prev_rank +from .initialize import get_tensor_model_parallel_world_size, set_tensor_model_parallel_world_size +from .initialize import get_pipeline_model_parallel_world_size, set_pipeline_model_parallel_world_size +from .initialize import get_virtual_pipeline_model_parallel_rank, set_virtual_pipeline_model_parallel_rank +from .initialize import initialize_model_parallel +from .initialize import model_parallel_is_initialized +from .initialize import get_model_parallel_world_size, get_model_parallel_rank +from .initialize import _set_global_memory_buffer + +from .layers import ColumnParallelLinear +from .layers import RowParallelLinear +from .layers import VocabParallelEmbedding +from .layers import (set_tensor_model_parallel_attributes, + set_defaults_if_not_set_tensor_model_parallel_attributes, + copy_tensor_model_parallel_attributes) + +from .mappings import copy_to_tensor_model_parallel_region +from .mappings import gather_from_tensor_model_parallel_region +from .mappings import reduce_from_tensor_model_parallel_region +from .mappings import scatter_to_tensor_model_parallel_region +from .mappings import gather_from_tensor_model_parallel_region +from .mappings import scatter_to_sequence_parallel_region +from .mappings import gather_from_sequence_parallel_region +from .mappings import reduce_scatter_to_sequence_parallel_region + +from .random import checkpoint +from .random import get_cuda_rng_tracker +from .random import init_checkpointed_activations_memory_buffer +from .random import model_parallel_cuda_manual_seed +from .random import reset_checkpointed_activations_memory_buffer +from .random import gather_split_1d_tensor +from .random import split_tensor_into_1d_equal_chunks + +from .utils import divide +from .utils import split_tensor_along_last_dim diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/cross_entropy.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/cross_entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..432fe8dc655e40387200bc84604c5812a49b86d0 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/cross_entropy.py @@ -0,0 +1,107 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import torch + +from .initialize import get_tensor_model_parallel_group +from .initialize import get_tensor_model_parallel_rank +from .initialize import get_tensor_model_parallel_world_size +from .utils import VocabUtility + +class _VocabParallelCrossEntropy(torch.autograd.Function): + + @staticmethod + def forward(ctx, vocab_parallel_logits, target): + # Maximum value along vocab dimension across all GPUs. + logits_max = torch.max(vocab_parallel_logits, dim=-1)[0] + torch.distributed.all_reduce(logits_max, + op=torch.distributed.ReduceOp.MAX, + group=get_tensor_model_parallel_group()) + # Subtract the maximum value. + vocab_parallel_logits.sub_(logits_max.unsqueeze(dim=-1)) + + # Get the partition's vocab indecies + get_vocab_range = VocabUtility.vocab_range_from_per_partition_vocab_size + partition_vocab_size = vocab_parallel_logits.size()[-1] + rank = get_tensor_model_parallel_rank() + world_size = get_tensor_model_parallel_world_size() + vocab_start_index, vocab_end_index = get_vocab_range( + partition_vocab_size, rank, world_size) + + # Create a mask of valid vocab ids (1 means it needs to be masked). + target_mask = (target < vocab_start_index) | (target >= vocab_end_index) + masked_target = target.clone() - vocab_start_index + masked_target[target_mask] = 0 + + # Get predicted-logits = logits[target]. + # For Simplicity, we convert logits to a 2-D tensor with size + # [*, partition-vocab-size] and target to a 1-D tensor of size [*]. + logits_2d = vocab_parallel_logits.view(-1, partition_vocab_size) + masked_target_1d = masked_target.view(-1) + arange_1d = torch.arange(start=0, end=logits_2d.size()[0], + device=logits_2d.device) + predicted_logits_1d = logits_2d[arange_1d, masked_target_1d] + predicted_logits_1d = predicted_logits_1d.clone().contiguous() + predicted_logits = predicted_logits_1d.view_as(target) + predicted_logits[target_mask] = 0.0 + # All reduce is needed to get the chunks from other GPUs. + torch.distributed.all_reduce(predicted_logits, + op=torch.distributed.ReduceOp.SUM, + group=get_tensor_model_parallel_group()) + # Sum of exponential of logits along vocab dimension across all GPUs. + exp_logits = vocab_parallel_logits + torch.exp(vocab_parallel_logits, out=exp_logits) + sum_exp_logits = exp_logits.sum(dim=-1) + torch.distributed.all_reduce(sum_exp_logits, + op=torch.distributed.ReduceOp.SUM, + group=get_tensor_model_parallel_group()) + # Loss = log(sum(exp(logits))) - predicted-logit. + loss = torch.log(sum_exp_logits) - predicted_logits + + # Store softmax, target-mask and masked-target for backward pass. + exp_logits.div_(sum_exp_logits.unsqueeze(dim=-1)) + ctx.save_for_backward(exp_logits, target_mask, masked_target_1d) + + return loss + + @staticmethod + def backward(ctx, grad_output): + + # Retreive tensors from the forward path. + softmax, target_mask, masked_target_1d = ctx.saved_tensors + + # All the inputs have softmax as thier gradient. + grad_input = softmax + # For simplicity, work with the 2D gradient. + partition_vocab_size = softmax.size()[-1] + grad_2d = grad_input.view(-1, partition_vocab_size) + + # Add the gradient from matching classes. + arange_1d = torch.arange(start=0, end=grad_2d.size()[0], + device=grad_2d.device) + grad_2d[arange_1d, masked_target_1d] -= ( + 1.0 - target_mask.view(-1).float()) + + # Finally elementwise multiplication with the output gradients. + grad_input.mul_(grad_output.unsqueeze(dim=-1)) + + return grad_input, None + + +def vocab_parallel_cross_entropy(vocab_parallel_logits, target): + """Helper function for the cross entropy.""" + return _VocabParallelCrossEntropy.apply(vocab_parallel_logits, target) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/data.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/data.py new file mode 100644 index 0000000000000000000000000000000000000000..846694b2c3f2541272433ec2f6daafaa9c166433 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/data.py @@ -0,0 +1,130 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from .initialize import get_tensor_model_parallel_group +from .initialize import get_tensor_model_parallel_rank +from .initialize import get_tensor_model_parallel_src_rank +from megatron.global_vars import get_current_device +import functools + + +_MAX_DATA_DIM = 5 +_GLOBAL_CACHED_BROADCAST_SIZES = [] + + +def _check_data_types(keys, data, target_dtype): + """Check that all the keys have the same target data type.""" + for key in keys: + assert data[key].dtype == target_dtype, '{} has data type {} which '\ + 'is different than {}'.format(key, data[key].dtype, target_dtype) + +def reset_cached_broadcast_sizes(): + global _GLOBAL_CACHED_BROADCAST_SIZES + _GLOBAL_CACHED_BROADCAST_SIZES = [] + +def broadcast_sizes(sizes): + global _GLOBAL_CACHED_BROADCAST_SIZES + if not _GLOBAL_CACHED_BROADCAST_SIZES: + # Move to GPU and broadcast. + sizes_cuda = torch.IntTensor(sizes).to(get_current_device()) + torch.distributed.broadcast(sizes_cuda, get_tensor_model_parallel_src_rank(), + group=get_tensor_model_parallel_group()) + # Move back to cpu and unpack. + _GLOBAL_CACHED_BROADCAST_SIZES = sizes_cuda.tolist() + return _GLOBAL_CACHED_BROADCAST_SIZES + +def _build_key_size_numel_dictionaries(keys, data): + """Build the size on rank 0 and broadcast.""" + max_dim = _MAX_DATA_DIM + sizes = [0 for _ in range(max_dim) for _ in keys] + + # Pack the sizes on rank zero. + if get_tensor_model_parallel_rank() == 0: + offset = 0 + for key in keys: + assert data[key].dim() < max_dim, 'you should increase MAX_DATA_DIM' + size = data[key].size() + for i, s in enumerate(size): + sizes[i + offset] = s + offset += max_dim + + sizes_cpu = broadcast_sizes(sizes) + if get_tensor_model_parallel_rank() == 0: + assert sizes_cpu == sizes, "sizes have changed and not broadcast to other ranks" + key_size = {} + key_numel = {} + total_numel = 0 + offset = 0 + for key in keys: + i = 0 + size = [] + numel = 1 + while sizes_cpu[offset + i] > 0: + this_size = sizes_cpu[offset + i] + size.append(this_size) + numel *= this_size + i += 1 + key_size[key] = size + key_numel[key] = numel + total_numel += numel + offset += max_dim + + return key_size, key_numel, total_numel + + +def broadcast_data(keys, data, datatype): + """Broadcast data from rank zero of each model parallel group to the + members of the same model parallel group. + + Arguments: + keys: list of keys in the data disctionary to be broadcasted + data: data dictionary of string keys and cpu tensor values. + datatype: torch data type of all tensors in data associated + with keys. + """ + # Build (key, size) and (key, number of elements) dictionaries along + # with the total number of elements on all ranks. + key_size, key_numel, total_numel = _build_key_size_numel_dictionaries(keys, + data) + + # Pack on rank zero. + if get_tensor_model_parallel_rank() == 0: + # Check that all keys have the same data type. + _check_data_types(keys, data, datatype) + # Flatten the data associated with the keys + flatten_data = torch.cat( + [data[key].contiguous().view(-1) for key in keys], dim=0).to(get_current_device()) + else: + flatten_data = torch.empty(total_numel, + device=get_current_device(), + dtype=datatype) + + # Broadcast + torch.distributed.broadcast(flatten_data, get_tensor_model_parallel_src_rank(), + group=get_tensor_model_parallel_group()) + + # Unpack + output = {} + offset = 0 + for key in keys: + size = key_size[key] + numel = key_numel[key] + output[key] = flatten_data.narrow(0, offset, numel).view(size) + offset += numel + + return output diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/layers.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..4446e5c7c892e3b2442747dcd06b227c4bd59fdc --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/layers.py @@ -0,0 +1,663 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# Parts of the code here are adapted from PyTorch +# repo: https://github.com/pytorch/pytorch + + +import math + +import torch +import torch.nn.functional as F +import torch.nn.init as init +from torch.nn.parameter import Parameter + +from .initialize import get_tensor_model_parallel_rank +from .initialize import get_tensor_model_parallel_world_size +from .initialize import get_tensor_model_parallel_group +from .initialize import get_global_memory_buffer + +from .mappings import copy_to_tensor_model_parallel_region +from .mappings import gather_from_tensor_model_parallel_region +from .mappings import gather_from_sequence_parallel_region +from .mappings import reduce_from_tensor_model_parallel_region +from .mappings import scatter_to_tensor_model_parallel_region +from .mappings import reduce_scatter_to_sequence_parallel_region + +from .random import get_cuda_rng_tracker +from .utils import divide +from .utils import split_tensor_along_last_dim +from .utils import VocabUtility +from megatron.model.fused_layer_norm import MixedFusedLayerNorm as LayerNorm +from megatron import get_args, mpu +from megatron.global_vars import get_current_device, get_num_microbatches +import deepspeed.runtime.activation_checkpointing.checkpointing as ds_checkpointing +from typing import Optional +import os +import warnings + + +_MODEL_PARALLEL_ATTRIBUTE_DEFAULTS = {'tensor_model_parallel': False, + 'partition_dim': -1, + 'partition_stride': 1} + + +def param_is_not_tensor_parallel_duplicate(param): + return (hasattr(param, 'tensor_model_parallel') and + param.tensor_model_parallel) or ( + get_tensor_model_parallel_rank() == 0) + + +def set_tensor_model_parallel_attributes(tensor, is_parallel, dim, stride): + # Make sure the attributes are not set. + for attribute in _MODEL_PARALLEL_ATTRIBUTE_DEFAULTS: + assert not hasattr(tensor, attribute) + # Set the attributes. + setattr(tensor, 'tensor_model_parallel', is_parallel) + setattr(tensor, 'partition_dim', dim) + setattr(tensor, 'partition_stride', stride) + + +def set_defaults_if_not_set_tensor_model_parallel_attributes(tensor): + def maybe_set(attribute, value): + if not hasattr(tensor, attribute): + setattr(tensor, attribute, value) + for attribute in _MODEL_PARALLEL_ATTRIBUTE_DEFAULTS: + maybe_set(attribute, _MODEL_PARALLEL_ATTRIBUTE_DEFAULTS[attribute]) + + +def copy_tensor_model_parallel_attributes(destination_tensor, source_tensor): + def maybe_copy(attribute): + if hasattr(source_tensor, attribute): + setattr(destination_tensor, attribute, + getattr(source_tensor, attribute)) + for attribute in _MODEL_PARALLEL_ATTRIBUTE_DEFAULTS: + maybe_copy(attribute) + + +def _initialize_affine_weight_gpu(weight, init_method, + partition_dim, stride=1): + """Initialize affine weight for model parallel on GPU.""" + + set_tensor_model_parallel_attributes(tensor=weight, + is_parallel=True, + dim=partition_dim, + stride=stride) + + if ds_checkpointing.is_configured(): + global get_cuda_rng_tracker + get_cuda_rng_tracker = ds_checkpointing.get_cuda_rng_tracker + + with get_cuda_rng_tracker().fork(): + init_method(weight) + + +def _initialize_affine_weight_cpu(weight, output_size, input_size, + per_partition_size, partition_dim, + init_method, stride=1, + return_master_weight=False): + """Initialize affine weight for model parallel. + + Build the master weight on all processes and scatter + the relevant chunk.""" + + set_tensor_model_parallel_attributes(tensor=weight, + is_parallel=True, + dim=partition_dim, + stride=stride) + + # Initialize master weight + master_weight = torch.empty(output_size, input_size, + dtype=torch.float, + requires_grad=False) + init_method(master_weight) + args = get_args() + master_weight = master_weight.to(dtype=args.params_dtype) + + # Split and copy + per_partition_per_stride_size = divide(per_partition_size, stride) + weight_list = torch.split(master_weight, per_partition_per_stride_size, + dim=partition_dim) + rank = get_tensor_model_parallel_rank() + world_size = get_tensor_model_parallel_world_size() + my_weight_list = weight_list[rank::world_size] + + with torch.no_grad(): + torch.cat(my_weight_list, dim=partition_dim, out=weight) + if return_master_weight: + return master_weight + return None + + +# This class encapsulates the behavior related to two mechanisms: hpu graph and amax measuring interval +class FP8ModuleRunner(): + def __init__(self, module, hpu_graph_enabled: bool=True, measure_interval: int=1, cache_fp8_weight_fwd=False): + self.module = module + self.hpu_graph_enabled = hpu_graph_enabled + self.measure_interval = measure_interval + self.cache_fp8_weight_fwd = cache_fp8_weight_fwd + self.module_with_measurement = None + self.module_no_measurement = None + self.run_cnt = 0 + + @staticmethod + def _init_hpu_graph(module, input, weight, bias=None): + import habana_frameworks.torch as ht + fp8_meta = module.save_fp8_meta() + tmp_in = torch.zeros_like(input, requires_grad=input.requires_grad) + tmp_w = torch.zeros_like(weight, requires_grad=weight.requires_grad) + tmp_b = torch.zeros_like(bias, requires_grad=bias.requires_grad) if bias is not None else None + wrapped_module = ht.hpu.ModuleCacher(max_graphs=10)(model=module, inplace=False) + wrapped_module(tmp_in, tmp_w, tmp_b).cpu() + wrapped_module.load_fp8_meta(fp8_meta) + return wrapped_module + + def _is_first_microbatch(self): + if not self.cache_fp8_weight_fwd: + return None + + return self.run_cnt % get_num_microbatches() in [1,2] + + def __call__(self, input, weight, bias=None): + from habana_frameworks.torch.hpex.experimental.transformer_engine.fp8 import ( + set_measurement_mode, + is_fp8_enabled + ) + if not is_fp8_enabled(): + return self.module(input, weight, bias) + + self.run_cnt += 1 + measure = self.measure_interval == 1 or self.run_cnt % self.measure_interval == 1 + set_measurement_mode(manual=True, manual_value=measure) + + is_first_microbatch = self._is_first_microbatch() + + # In case of hpu graphs, do not record first iteration + if not self.hpu_graph_enabled or self.run_cnt == 1: + return self.module(input, weight, bias, is_first_microbatch=is_first_microbatch) + + assert is_first_microbatch==None, "is_first_microbatch handling not implemented with HPU graphs, turn off either hpu graphs or cache fp8 weight fwd" + + # HPU graphs case + if measure: + if self.module_with_measurement is None: + self.module_with_measurement = self._init_hpu_graph(self.module, input, weight, bias) + return self.module_with_measurement(input, weight, bias) + else: + if self.module_no_measurement is None: + self.module_no_measurement = self._init_hpu_graph(self.module, input, weight, bias) + return self.module_no_measurement(input, weight, bias) + + +class VocabParallelEmbedding(torch.nn.Module): + """Embedding parallelized in the vocabulary dimension. + + This is mainly adapted from torch.nn.Embedding and all the default + values are kept. + Arguments: + num_embeddings: vocabulary size. + embedding_dim: size of hidden state. + init_method: method to initialize weights. + """ + + def __init__(self, num_embeddings, embedding_dim, + init_method=init.xavier_normal_): + super(VocabParallelEmbedding, self).__init__() + # Keep the input dimensions. + self.num_embeddings = num_embeddings + self.embedding_dim = embedding_dim + # Set the defaults for compatibility. + self.padding_idx = None + self.max_norm = None + self.norm_type = 2. + self.scale_grad_by_freq = False + self.sparse = False + self._weight = None + self.tensor_model_parallel_size = get_tensor_model_parallel_world_size() + # Divide the weight matrix along the vocaburaly dimension. + self.vocab_start_index, self.vocab_end_index = \ + VocabUtility.vocab_range_from_global_vocab_size( + self.num_embeddings, get_tensor_model_parallel_rank(), + self.tensor_model_parallel_size) + self.num_embeddings_per_partition = self.vocab_end_index - \ + self.vocab_start_index + + # Allocate weights and initialize. + args = get_args() + + # only the first stage embedding runs this class' forward. The head's embedding does its own + # thing, so don't waste memory allocating LN weights. + self.layer_norm = None + if mpu.is_pipeline_first_stage() and args.embed_layernorm: + self.layer_norm = LayerNorm(embedding_dim) + + if args.use_cpu_initialization: + self.weight = Parameter(torch.empty( + self.num_embeddings_per_partition, self.embedding_dim, + dtype=args.params_dtype)) + _initialize_affine_weight_cpu( + self.weight, self.num_embeddings, self.embedding_dim, + self.num_embeddings_per_partition, 0, init_method) + else: + self.weight = Parameter(torch.empty( + self.num_embeddings_per_partition, self.embedding_dim, + device=get_current_device(), dtype=args.params_dtype)) + _initialize_affine_weight_gpu(self.weight, init_method, + partition_dim=0, stride=1) + + def forward(self, input_): + if self.tensor_model_parallel_size > 1: + # Build the mask. + input_mask = (input_ < self.vocab_start_index) | \ + (input_ >= self.vocab_end_index) + # Mask the input. + masked_input = input_.clone() - self.vocab_start_index + masked_input[input_mask] = 0 + else: + masked_input = input_ + # Get the embeddings. + output_parallel = F.embedding(masked_input, self.weight, + self.padding_idx, self.max_norm, + self.norm_type, self.scale_grad_by_freq, + self.sparse) + # Mask the output embedding. + if self.tensor_model_parallel_size > 1: + output_parallel[input_mask, :] = 0.0 + # Reduce across all the model parallel GPUs. + output = reduce_from_tensor_model_parallel_region(output_parallel) + + if self.layer_norm is not None: + output = self.layer_norm(output) + + return output + +class AllGather(torch.autograd.Function): + @staticmethod + def forward(ctx, input): + world_size = get_tensor_model_parallel_world_size() + ctx.size = input.size() + dim_size = list(input.size()) + dim_size[0] = dim_size[0] * world_size + + all_gather_buffer = \ + get_global_memory_buffer().get_tensor(dim_size, input.dtype, "mpu") + torch.distributed.all_gather_into_tensor( + all_gather_buffer, + input, + group=get_tensor_model_parallel_group(), + async_op=True) + + total_input = all_gather_buffer + return total_input + + @staticmethod + def backward(ctx, grad_output): + sub_grad_output = torch.empty(ctx.size, dtype=grad_output.dtype, + device=get_current_device(), + requires_grad=False) + + # reduce_scatter + torch.distributed.reduce_scatter_tensor(sub_grad_output, grad_output, + group=get_tensor_model_parallel_group(), + async_op=True) + return sub_grad_output + +def all_gather(input): + return AllGather().apply(input) + +def flatten_input(func): + def wrapper(input, weight, bias=None): + if input.dim() > 2: + input_size = input.size() + input = torch.flatten(input, start_dim=0, end_dim=input.dim()-2) + output = func(input, weight, bias) + output = torch.unflatten(output, dim=0, sizes=input_size[:-1]) + else: + output = func(input, weight, bias) + return output + return wrapper + +class VocabParallelProjection(torch.nn.Module): + """Projection parallelized in the vocabulary dimension. + + This is mainly adapted from VocabParallelEmbedding and parallel_lm_logits. + Arguments: + num_embeddings: vocabulary size. + embedding_dim: size of hidden state. + parallel_output: whether to output parallel outputs + init_method: method to initialize weights. + """ + + def __init__(self, num_embeddings, embedding_dim, parallel_output=True, + init_method=init.xavier_normal_): + super(VocabParallelProjection, self).__init__() + # Keep the input dimensions. + self.num_embeddings = num_embeddings + self.embedding_dim = embedding_dim + self.parallel_output = parallel_output + # Set the defaults for compatibility. + self._weight = None + self.bias = None + self.tensor_model_parallel_size = get_tensor_model_parallel_world_size() + # Divide the weight matrix along the vocaburaly dimension. + self.vocab_start_index, self.vocab_end_index = \ + VocabUtility.vocab_range_from_global_vocab_size( + self.num_embeddings, get_tensor_model_parallel_rank(), + self.tensor_model_parallel_size) + self.num_embeddings_per_partition = self.vocab_end_index - \ + self.vocab_start_index + + # Allocate weights and initialize. + args = get_args() + + if args.use_cpu_initialization: + self.weight = Parameter(torch.empty( + self.num_embeddings_per_partition, self.embedding_dim, + dtype=args.params_dtype)) + _initialize_affine_weight_cpu( + self.weight, self.num_embeddings, self.embedding_dim, + self.num_embeddings_per_partition, 0, init_method) + else: + self.weight = Parameter(torch.empty( + self.num_embeddings_per_partition, self.embedding_dim, + device=get_current_device(), dtype=args.params_dtype)) + _initialize_affine_weight_gpu(self.weight, init_method, + partition_dim=0, stride=1) + + def forward(self, input_): + """LM logits using word projection weights.""" + # Parallel logits. + input_parallel = mpu.copy_to_tensor_model_parallel_region(input_) + # Matrix multiply. + if self.bias is None: + logits_parallel = F.linear(input_parallel, self.weight) + else: + logits_parallel = F.linear(input_parallel, self.weight, self.bias) + # Gather if needed. + if self.parallel_output: + return logits_parallel + + return mpu.gather_from_tensor_model_parallel_region(logits_parallel) + + +class ColumnParallelLinear(torch.nn.Module): + """Linear layer with column parallelism. + + The linear layer is defined as Y = XA + b. A is parallelized along + its second dimension as A = [A_1, ..., A_p]. + + Arguments: + input_size: first dimension of matrix A. + output_size: second dimension of matrix A. + bias: If true, add bias + gather_output: If true, call all-gather on output and make Y available + to all GPUs, otherwise, every GPU will have its output + which is Y_i = XA_i + init_method: method to initialize weights. Note that bias is always set + to zero. + stride: For the strided linear layers. + keep_master_weight_for_test: This was added for testing and should be + set to False. It returns the master weights + used for initialization. + skip_bias_add: This was added to enable performance optimations where bias + can be fused with other elementwise operations. we skip + adding bias but instead return it. + sequence_parallel: Indicates that sequence parallelism is used. + """ + + def __init__(self, input_size, output_size, + bias=True, gather_output=True, + init_method=init.xavier_normal_, + stride=1, keep_master_weight_for_test=False, + sequence_parallel=False, moe=False, + enable_expert_tensor_parallelism=False + ): + super(ColumnParallelLinear, self).__init__() + + # Keep input parameters + self.input_size = input_size + self.output_size = output_size + self.gather_output = gather_output + # Divide the weight matrix along the last dimension. + if moe and (not enable_expert_tensor_parallelism): + world_size = 1 + self.is_expert_without_slicing = True + else: + world_size = get_tensor_model_parallel_world_size() + self.is_expert_without_slicing = False + + self.output_size_per_partition = divide(output_size, world_size) + + # Parameters. + # Note: torch.nn.functional.linear performs XA^T + b and as a result + # we allocate the transpose. + # Initialize weight. + args = get_args() + self.sequence_parallel = sequence_parallel + + if args.use_cpu_initialization: + self.weight = Parameter(torch.empty(self.output_size_per_partition, + self.input_size, + dtype=args.params_dtype)) + self.master_weight = _initialize_affine_weight_cpu( + self.weight, self.output_size, self.input_size, + self.output_size_per_partition, 0, init_method, + stride=stride, return_master_weight=keep_master_weight_for_test) + else: + self.weight = Parameter(torch.empty( + self.output_size_per_partition, self.input_size, + device=get_current_device(), dtype=args.params_dtype)) + _initialize_affine_weight_gpu(self.weight, init_method, + partition_dim=0, stride=stride) + + if bias: + if args.use_cpu_initialization: + self.bias = Parameter(torch.empty( + self.output_size_per_partition, dtype=args.params_dtype)) + else: + self.bias = Parameter(torch.zeros( + self.output_size_per_partition, + device=get_current_device(), + dtype=args.params_dtype)) + set_tensor_model_parallel_attributes(self.bias, True, 0, stride) + else: + self.register_parameter('bias', None) + + import habana_frameworks.torch.hpex.experimental.transformer_engine as te + output_parallel_linear = te.Linear( + self.input_size, + self.output_size_per_partition, + skip_weight_param_allocation=True, + bias = True, + minimize_memory=not args.cache_fp8_weight) + self.output_parallel_linear = FP8ModuleRunner( + output_parallel_linear, + args.use_hpu_graphs, + args.hpu_fp8_measure_interval, + args.cache_fp8_weight_fwd) + + if self.sequence_parallel: + if world_size <= 1: + warnings.warn( + "`sequence_parallel_enabled` is set to `True`, " + f"but tensor model parallel size is {world_size}. " + f"Disabling sequence parallel." + ) + self.sequence_parallel = False + + def forward(self, input_): + # Set up backprop all-reduce. + if self.is_expert_without_slicing or self.sequence_parallel: + input_parallel = input_ + else: + input_parallel = copy_to_tensor_model_parallel_region(input_) + + gather_input = lambda x: x + if self.sequence_parallel: + gather_input = all_gather + + # Matrix multiply. + output_parallel = flatten_input(self.output_parallel_linear)(gather_input(input_parallel), self.weight, self.bias) + + if self.gather_output and not self.is_expert_without_slicing: + # All-gather across the partitions. + assert not self.sequence_parallel + output = gather_from_tensor_model_parallel_region(output_parallel) + else: + output = output_parallel + return output + + +class RowParallelLinear(torch.nn.Module): + """Linear layer with row parallelism. + + The linear layer is defined as Y = XA + b. A is parallelized along + its first dimension and X along its second dimension as: + - - + | A_1 | + | . | + A = | . | X = [X_1, ..., X_p] + | . | + | A_p | + - - + Arguments: + input_size: first dimension of matrix A. + output_size: second dimension of matrix A. + bias: If true, add bias. Note that bias is not parallelized. + input_is_parallel: If true, we assume that the input is already + split across the GPUs and we do not split + again. + init_method: method to initialize weights. Note that bias is always set + to zero. + stride: For the strided linear layers. + keep_master_weight_for_test: This was added for testing and should be + set to False. It returns the master weights + used for initialization. + skip_bias_add: This was added to enable performance optimization where bias + can be fused with other elementwise operations. We skip + adding bias but instead return it. + sequence_parallel: Indicates that sequence parallelism is used. + """ + + def __init__(self, input_size, output_size, + bias=True, input_is_parallel=False, + init_method=init.xavier_normal_, stride=1, + keep_master_weight_for_test=False, + skip_bias_add=False, + sequence_parallel=False, + moe=False, + enable_expert_tensor_parallelism=False + ): + super(RowParallelLinear, self).__init__() + + # Keep input parameters + self.input_size = input_size + self.output_size = output_size + self.input_is_parallel = input_is_parallel + # Divide the weight matrix along the last dimension. + + if moe and (not enable_expert_tensor_parallelism): + world_size = 1 + else: + world_size = get_tensor_model_parallel_world_size() + + self.is_expert_without_slicing = moe and world_size==1 + + self.input_size_per_partition = divide(input_size, world_size) + self.skip_bias_add = skip_bias_add + self.sequence_parallel = sequence_parallel + + if self.sequence_parallel and not self.input_is_parallel: + raise RuntimeError("To enable `sequence_parallel_enabled`, `input_is_parallel` must be `True`") + + # Parameters. + # Note: torch.nn.functional.linear performs XA^T + b and as a result + # we allocate the transpose. + # Initialize weight. + args = get_args() + self.args = args + if args.use_cpu_initialization: + self.weight = Parameter(torch.empty(self.output_size, + self.input_size_per_partition, + dtype=args.params_dtype)) + self.master_weight = _initialize_affine_weight_cpu( + self.weight, self.output_size, self.input_size, + self.input_size_per_partition, 1, init_method, + stride=stride, return_master_weight=keep_master_weight_for_test) + else: + self.weight = Parameter(torch.empty( + self.output_size, self.input_size_per_partition, + device=get_current_device(), dtype=args.params_dtype)) + _initialize_affine_weight_gpu(self.weight, init_method, + partition_dim=1, stride=stride) + if bias: + if args.use_cpu_initialization: + self.bias = Parameter(torch.empty(self.output_size, + dtype=args.params_dtype)) + else: + self.bias = Parameter(torch.empty( + self.output_size, device=get_current_device(), + dtype=args.params_dtype)) + if self.sequence_parallel: + setattr(self.bias, 'sequence_parallel', True) + + # Always initialize bias to zero. + with torch.no_grad(): + self.bias.zero_() + else: + self.register_parameter('bias', None) + + import habana_frameworks.torch.hpex.experimental.transformer_engine as te + output_parallel_linear = te.Linear( + self.input_size_per_partition, + self.output_size, + skip_weight_param_allocation=True, + bias=False, + minimize_memory=not args.cache_fp8_weight) + self.output_parallel_linear = FP8ModuleRunner( + output_parallel_linear, + args.use_hpu_graphs, + args.hpu_fp8_measure_interval, + args.cache_fp8_weight_fwd) + + + def forward(self, input_): + # Set up backprop all-reduce. + if self.input_is_parallel or self.is_expert_without_slicing: + input_parallel = input_ + else: + assert not self.sequence_parallel + input_parallel = scatter_to_tensor_model_parallel_region(input_) + + # Matrix multiply. + output_parallel = flatten_input(self.output_parallel_linear)(input_parallel, self.weight) + + if self.sequence_parallel: + output_ = reduce_scatter_to_sequence_parallel_region(output_parallel) + else: + if self.is_expert_without_slicing: # non-expert only tensor-parallelism + output_ = output_parallel + else: + output_ = reduce_from_tensor_model_parallel_region(output_parallel) + + if not self.skip_bias_add: + output = output_ + self.bias if self.bias is not None else output_ + output_bias = None + else: + output = output_ + output_bias = self.bias + return output, output_bias diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/mappings.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/mappings.py new file mode 100644 index 0000000000000000000000000000000000000000..f54c63ee0915a88aa7fb18536cc7a8afae134c3a --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/mappings.py @@ -0,0 +1,289 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from megatron.global_vars import get_current_device +from .initialize import get_tensor_model_parallel_group, get_tensor_model_parallel_world_size, get_tensor_model_parallel_rank +from .utils import split_tensor_along_last_dim + +def _reduce(input_): + """All-reduce the the input tensor across model parallel group.""" + + # Bypass the function if we are using only 1 GPU. + if get_tensor_model_parallel_world_size()==1: + return input_ + + # All-reduce. + torch.distributed.all_reduce(input_, group=get_tensor_model_parallel_group()) + + return input_ + + +def _split_along_last_dim(input_): + """Split the tensor along its last dimension and keep the + corresponding slice.""" + + world_size = get_tensor_model_parallel_world_size() + # Bypass the function if we are using only 1 GPU. + if world_size==1: + return input_ + + # Split along last dimension. + input_list = split_tensor_along_last_dim(input_, world_size) + + # Note: torch.split does not create contiguous tensors by default. + rank = get_tensor_model_parallel_rank() + output = input_list[rank].contiguous() + + return output + + +def _split_along_first_dim(input_): + """Split the tensor along its first dimension and keep the + corresponding slice.""" + + world_size = get_tensor_model_parallel_world_size() + # Bypass the function if we are using only 1 GPU. + if world_size == 1: + return input_ + + # Split along first dimension. + dim_size = input_.size()[0] + assert dim_size % world_size == 0, \ + "First dimension of the tensor should be divisible by tensor parallel size" + local_dim_size = dim_size // world_size + rank = get_tensor_model_parallel_rank() + dim_offset = rank * local_dim_size + + output = input_[dim_offset:dim_offset + local_dim_size].contiguous() + + return output + + +def _gather_along_last_dim(input_): + """Gather tensors and concatinate along the last dimension.""" + + world_size = get_tensor_model_parallel_world_size() + # Bypass the function if we are using only 1 GPU. + if world_size==1: + return input_ + + # Size and dimension. + last_dim = input_.dim() - 1 + rank = get_tensor_model_parallel_rank() + + tensor_list = [torch.empty_like(input_) for _ in range(world_size)] + tensor_list[rank] = input_ + torch.distributed.all_gather(tensor_list, input_, group=get_tensor_model_parallel_group()) + + # Note: torch.cat already creates a contiguous tensor. + output = torch.cat(tensor_list, dim=last_dim).contiguous() + + return output + + +def _gather_along_first_dim(input_): + """Gather tensors and concatinate along the first dimension.""" + + world_size = get_tensor_model_parallel_world_size() + # Bypass the function if we are using only 1 GPU. + if world_size == 1: + return input_ + + dim_size = list(input_.size()) + dim_size[0] = dim_size[0] * world_size + + output = torch.empty(dim_size, dtype=input_.dtype, + device=get_current_device()) + torch.distributed.all_gather_into_tensor(output, input_.contiguous(), + group=get_tensor_model_parallel_group()) + + return output + + +def _reduce_scatter_along_first_dim(input_): + """Reduce-scatter the input tensor across model parallel group.""" + world_size = get_tensor_model_parallel_world_size() + # Bypass the function if we are using only 1 GPU. + if world_size == 1: + return input_ + + dim_size = list(input_.size()) + assert dim_size[0] % world_size == 0, \ + "First dimension of the tensor should be divisible by tensor parallel size" + + dim_size[0] = dim_size[0] // world_size + + output = torch.empty(dim_size, dtype=input_.dtype, + device=get_current_device()) + torch.distributed.reduce_scatter_tensor(output, input_.contiguous(), + group=get_tensor_model_parallel_group()) + return output + + +class _CopyToModelParallelRegion(torch.autograd.Function): + """Pass the input to the model parallel region.""" + + @staticmethod + def symbolic(graph, input_): + return input_ + + @staticmethod + def forward(ctx, input_): + return input_ + + @staticmethod + def backward(ctx, grad_output): + return _reduce(grad_output) + + +class _ReduceFromModelParallelRegion(torch.autograd.Function): + """All-reduce the input from the model parallel region.""" + + @staticmethod + def symbolic(graph, input_): + return _reduce(input_) + + @staticmethod + def forward(ctx, input_): + return _reduce(input_) + + @staticmethod + def backward(ctx, grad_output): + return grad_output + + +class _ScatterToModelParallelRegion(torch.autograd.Function): + """Split the input and keep only the corresponding chuck to the rank.""" + + @staticmethod + def symbolic(graph, input_): + return _split_along_last_dim(input_) + + @staticmethod + def forward(ctx, input_): + return _split_along_last_dim(input_) + + @staticmethod + def backward(ctx, grad_output): + return _gather_along_last_dim(grad_output) + + +class _GatherFromModelParallelRegion(torch.autograd.Function): + """Gather the input from model parallel region and concatinate.""" + + @staticmethod + def symbolic(graph, input_): + return _gather_along_last_dim(input_) + + @staticmethod + def forward(ctx, input_): + return _gather_along_last_dim(input_) + + @staticmethod + def backward(ctx, grad_output): + return _split_along_last_dim(grad_output) + + +class _ScatterToSequenceParallelRegion(torch.autograd.Function): + """Split the input and keep only the corresponding chunck to the rank.""" + + @staticmethod + def symbolic(graph, input_): + return _split_along_first_dim(input_) + + @staticmethod + def forward(ctx, input_): + return _split_along_first_dim(input_) + + @staticmethod + def backward(ctx, grad_output): + return _gather_along_first_dim(grad_output) + + +class _GatherFromSequenceParallelRegion(torch.autograd.Function): + """Gather the input from sequence parallel region and concatinate.""" + + @staticmethod + def symbolic(graph, input_, tensor_parallel_output_grad=True): + return _gather_along_first_dim(input_) + + @staticmethod + def forward(ctx, input_, tensor_parallel_output_grad=True): + ctx.tensor_parallel_output_grad = tensor_parallel_output_grad + return _gather_along_first_dim(input_) + + @staticmethod + def backward(ctx, grad_output): + tensor_parallel_output_grad = ctx.tensor_parallel_output_grad + + # If the computation graph after the gather operation is + # in the tensor parallel mode, output gradients need to reduce + # scattered and whereas if the computation is duplicated, + # output gradients need to be scattered. + if tensor_parallel_output_grad: + return _reduce_scatter_along_first_dim(grad_output), None + else: + return _split_along_first_dim(grad_output), None + + +class _ReduceScatterToSequenceParallelRegion(torch.autograd.Function): + """Reduce scatter the input from the model parallel region.""" + + @staticmethod + def symbolic(graph, input_): + return _reduce_scatter_along_first_dim(input_) + + @staticmethod + def forward(ctx, input_): + return _reduce_scatter_along_first_dim(input_) + + @staticmethod + def backward(ctx, grad_output): + return _gather_along_first_dim(grad_output) + + +# ----------------- +# Helper functions. +# ----------------- + +def copy_to_tensor_model_parallel_region(input_): + return _CopyToModelParallelRegion.apply(input_) + + +def reduce_from_tensor_model_parallel_region(input_): + return _ReduceFromModelParallelRegion.apply(input_) + + +def scatter_to_tensor_model_parallel_region(input_): + return _ScatterToModelParallelRegion.apply(input_) + + +def gather_from_tensor_model_parallel_region(input_): + return _GatherFromModelParallelRegion.apply(input_) + + +def scatter_to_sequence_parallel_region(input_): + return _ScatterToSequenceParallelRegion.apply(input_) + + +def gather_from_sequence_parallel_region(input_, tensor_parallel_output_grad=True): + return _GatherFromSequenceParallelRegion.apply(input_, tensor_parallel_output_grad) + + +def reduce_scatter_to_sequence_parallel_region(input_): + return _ReduceScatterToSequenceParallelRegion.apply(input_) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/random.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/random.py new file mode 100644 index 0000000000000000000000000000000000000000..ea8c68e444d6a21ccaa341bc82db4ab1f19d48d3 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/random.py @@ -0,0 +1,448 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# Parts of the code here are adapted from PyTorch +# repo: https://github.com/pytorch/pytorch + +import contextlib + +import torch +from torch import _C +from torch.cuda import _lazy_call, device as device_ctx_manager +from torch.utils.checkpoint import detach_variable + +from megatron import get_args +from megatron.memory import allocate_mem_buff +from megatron.global_vars import get_current_device_index + +from .initialize import get_data_parallel_rank +from .initialize import get_tensor_model_parallel_group +from .initialize import get_tensor_model_parallel_rank +from .initialize import get_tensor_model_parallel_world_size + +import copy + + +# Default name for the model parallel rng tracker. +_MODEL_PARALLEL_RNG_TRACKER_NAME = 'model-parallel-rng' + + +# Whether apply model parallelsim to checkpointed hidden states. +_CHECKPOINTED_ACTIVATIONS_MEMORY_BUFFER = None + + +def init_checkpointed_activations_memory_buffer(): + """Initializ the memory buffer for the checkpointed activations.""" + args = get_args() + + assert args.micro_batch_size == args.eval_micro_batch_size, \ + "init_checkpointed_activations_memory_buffer - Unsupported for split micro batch size" + per_layer = args.micro_batch_size * args.max_position_embeddings * \ + args.hidden_size // args.tensor_model_parallel_size + assert args.num_layers % args.checkpoint_num_layers == 0, \ + 'number of layers is not divisible by checkpoint-num-layers' + num_checkpointer_layers = args.num_layers // args.checkpoint_num_layers + numel = per_layer * num_checkpointer_layers + dtype = torch.half + if not args.fp16: + dtype = torch.float + + global _CHECKPOINTED_ACTIVATIONS_MEMORY_BUFFER + assert _CHECKPOINTED_ACTIVATIONS_MEMORY_BUFFER is None, \ + 'checkpointed activations memory buffer is already allocated.' + _CHECKPOINTED_ACTIVATIONS_MEMORY_BUFFER = allocate_mem_buff( + 'checkpointed activations', numel, dtype, track_usage=False) + + +def reset_checkpointed_activations_memory_buffer(): + """Reset the memory used for checkpointing.""" + if _CHECKPOINTED_ACTIVATIONS_MEMORY_BUFFER is not None: + _CHECKPOINTED_ACTIVATIONS_MEMORY_BUFFER.reset() + + +def _set_cuda_rng_state(new_state, device=-1): + """Sets the random number generator state of the current GPU. + + Argumentss: + new_state (torch.ByteTensor): The desired state + This function is adapted from PyTorch repo (torch.cuda.set_rng_state) + with a single change: the input state is not cloned. Cloning caused + major performance issues for +4 GPU cases. + """ + if hasattr(_C, '_cuda_setRNGState') and callable(_C._cuda_setRNGState): + # older PyTorch + def cb(): + with device_ctx_manager(device): + _C._cuda_setRNGState(new_state) + else: + # newer PyTorch + if device == -1: + device = torch.device('cuda') + elif isinstance(device, str): + device = torch.device(device) + elif isinstance(device, int): + device = torch.device('cuda', device) + + def cb(): + idx = device.index + if idx is None: + idx = get_current_device_index() + default_generator = torch.cuda.default_generators[idx] + default_generator.set_state(new_state) + + _lazy_call(cb) + + +def split_tensor_into_1d_equal_chunks(tensor): + """Break a tensor into equal 1D chunks.""" + data = tensor.view(-1) + partition_size = torch.numel(data) // get_tensor_model_parallel_world_size() + start_index = partition_size * get_tensor_model_parallel_rank() + end_index = start_index + partition_size + return data[start_index:end_index] + + +def gather_split_1d_tensor(tensor): + """Opposite of above function, gather values from model parallel ranks.""" + world_size = get_tensor_model_parallel_world_size() + numel = torch.numel(tensor) + numel_gathered = world_size * numel + gathered = torch.empty(numel_gathered, dtype=tensor.dtype, + device=torch.cuda.current_device(), + requires_grad=False) + chunks = [gathered[i*numel:(i+1)*numel] for i in range(world_size)] + torch.distributed.all_gather(chunks, tensor, + group=get_tensor_model_parallel_group()) + return gathered + + +class CudaRNGStatesTracker: + """Tracker for the cuda RNG states. + + Using the `add` method, a cuda rng state is initialized based on + the input `seed` and is assigned to `name`. Later, by forking the + rng state, we can perform operations and return to our starting + cuda state. + """ + + def __init__(self): + # Map from a string name to the cuda rng state. + self.states_ = {} + # Seeds are just for book keeping and ensure no seed is set twice. + self.seeds_ = set() + + def reset(self): + """Set to the initial state (no tracker).""" + self.states_ = {} + self.seeds_ = set() + + def get_states(self): + """Get rng states. Copy the dictionary so we have direct + pointers to the states, not just a pointer to the dictionary.""" + states = {} + for name in self.states_: + states[name] = self.states_[name] + return states + + def set_states(self, states): + """Set the rng states. For efficiency purposes, we do not check + the size of seed for compatibility.""" + self.states_ = states + + def add(self, name, seed): + """Track the rng state.""" + # Check seed is not already used. + if seed in self.seeds_: + raise Exception('seed {} already exists'.format(seed)) + self.seeds_.add(seed) + # Check that state is not already defined. + if name in self.states_: + raise Exception('cuda rng state {} already exists'.format(name)) + # Get the current rng state. + orig_rng_state = torch.cuda.get_rng_state() + # Set the new state and store it. + torch.cuda.manual_seed(seed) + self.states_[name] = torch.cuda.get_rng_state() + # Reset rng state to what it was. + _set_cuda_rng_state(orig_rng_state) + + @contextlib.contextmanager + def fork(self, name=_MODEL_PARALLEL_RNG_TRACKER_NAME): + """Fork the cuda rng state, perform operations, and exit with + the original state.""" + # Check if we have added the state + if name not in self.states_: + print(name, self.states_) + raise Exception('cuda rng state {} is not added'.format(name)) + # Store current rng state. + orig_cuda_rng_state = torch.cuda.get_rng_state() + # Set rng state to the desired one + _set_cuda_rng_state(self.states_[name]) + # Do the stuff we wanted to do. + try: + yield + finally: + # Update the current rng state for later use. + self.states_[name] = torch.cuda.get_rng_state() + # And set the state to the original state we started with. + _set_cuda_rng_state(orig_cuda_rng_state) + +def _set_hpu_rng_state(new_state, device=-1): + """Sets the random number generator state of the current HPU. + + Arguments: + new_state (torch.ByteTensor): The desired state + This function is adapted from PyTorch repo (torch.set_rng_state) + with a single change: the input state is not cloned. Cloning caused + major performance issues for +4 HPU cases. + """ + # newer PyTorch + if device == -1: + device = torch.device('hpu') + elif isinstance(device, str): + device = torch.device(device) + elif isinstance(device, int): + device = torch.device('hpu', device) + + def cb(): + import habana_frameworks.torch.hpu as _hpu + idx = device.index + if idx is None: + idx = _hpu.current_device() + default_generator = _hpu.random.default_generators[idx] + default_generator.set_state(new_state) + + cb() + +class RNGStatesTracker: + """Tracker for the device RNG states. + + Using the `add` method, a device rng state is initialized based on + the input `seed` and is assigned to `name`. Later, by forking the + rng state, we can perform operations and return to our starting + device state. + """ + def __init__(self): + + self.device_initialized = False + # Map from a string name to the device rng state. + self.states_ = {} + # Seeds are just for book keeping and ensure no seed is set twice. + self.seeds_ = set() + @staticmethod + def get_state_fnc(device = 'hpu'): + import habana_frameworks.torch.hpu.random as hpu_random + return hpu_random.get_rng_state(device) + @staticmethod + def set_state_fnc(new_state: torch.Tensor, device = 'hpu'): + import habana_frameworks.torch.hpu.random as hpu_random + return hpu_random.set_rng_state(new_state, device) + @staticmethod + def manual_seed(seed) -> torch._C.Generator: + import habana_frameworks.torch.hpu.random as hpu_random + return hpu_random.manual_seed(seed) + @staticmethod + def set_rng_state(new_state, device=-1): + return _set_hpu_rng_state(new_state, device) + + def reset(self): + """Set to the initial state (no tracker).""" + self.states_ = {} + self.seeds_ = set() + + def get_states(self): + """Get rng states. Copy the dictionary so we have direct + pointers to the states, not just a pointer to the dictionary.""" + return copy.copy(self.states_) + + def set_states(self, states): + """Set the rng states. For efficiency purposes, we do not check + the size of seed for compatibility.""" + self.states_ = states + + def add(self, name, seed): + """Track the rng state.""" + # Check seed is not already used. + if seed in self.seeds_: + raise Exception('seed {} already exists'.format(seed)) + self.seeds_.add(seed) + # Check that state is not already defined. + if name in self.states_: + raise Exception('device rng state {} already exists'.format(name)) + # Get the current rng state. + orig_rng_state = self.get_state_fnc() + # Set the new state and store it. + self.manual_seed(seed) + self.states_[name] = self.get_state_fnc() + # Reset rng state to what it was. + self.set_rng_state(orig_rng_state) + + @contextlib.contextmanager + def fork(self, name=_MODEL_PARALLEL_RNG_TRACKER_NAME): + """Fork the device rng state, perform operations, and exit with + the original state.""" + # Check if we have added the state + if name not in self.states_: + raise Exception('device rng state {} is not added'.format(name)) + # Store current rng state. + orig_device_rng_state = self.get_state_fnc() + # Set rng state to the desired one + self.set_rng_state(self.states_[name]) + # Do the stuff we wanted to do. + try: + yield + finally: + # Update the current rng state for later use. + self.states_[name] = self.get_state_fnc() + # And set the state to the original state we started with. + self.set_rng_state(orig_device_rng_state) + + +class RNGStatesTrackerSingleton: + tracker = None + def __new__(self): + if not hasattr(self, 'instance'): + self.instance = super().__new__(self) + return self.instance + + def get(self): + if not self.tracker: + if get_args().use_hpu: + self.tracker = RNGStatesTracker() + else: + self.tracker = CudaRNGStatesTracker() + return self.tracker + +def get_cuda_rng_tracker(): + """Get cuda rng tracker.""" + t = RNGStatesTrackerSingleton() + return t.get() + + +def model_parallel_cuda_manual_seed(seed): + """Initialize model parallel cuda seed. + + This function should be called after the model parallel is + initialized. Also, no torch.cuda.manual_seed should be called + after this function. Basically, this is replacement for that + function. + Two set of RNG states are tracked: + default state: This is for data parallelism and is the same among a + set of model parallel GPUs but different across + different model paralle groups. This is used for + example for dropout in the non-tensor-model-parallel regions. + tensor-model-parallel state: This state is different among a set of model + parallel GPUs, but the same across data parallel + groups. This is used for example for dropout in + model parallel regions. + """ + # 2718 is just for fun and any POSITIVE value will work. + offset = seed + 2718 + tensor_model_parallel_seed = offset + get_tensor_model_parallel_rank() + # Data parallel gets the original seed. + data_parallel_seed = seed + + if torch.distributed.get_rank() == 0: + print('> initializing model parallel cuda seeds on global rank {}, ' + 'model parallel rank {}, and data parallel rank {} with ' + 'model parallel seed: {} and data parallel seed: {}'.format( + torch.distributed.get_rank(), get_tensor_model_parallel_rank(), + get_data_parallel_rank(), tensor_model_parallel_seed, + data_parallel_seed), flush=True) + get_cuda_rng_tracker().reset() + # Set the default state. + torch.cuda.manual_seed(data_parallel_seed) + # and model parallel state. + get_cuda_rng_tracker().add(_MODEL_PARALLEL_RNG_TRACKER_NAME, + tensor_model_parallel_seed) + + +class CheckpointFunction(torch.autograd.Function): + """This function is adapted from torch.utils.checkpoint with + two main changes: + 1) torch.cuda.set_rng_state is replaced with `_set_cuda_rng_state` + 2) the states in the model parallel tracker are also properly + tracked/set/reset. + """ + @staticmethod + def forward(ctx, run_function, *args): + ctx.run_function = run_function + + # Copy the rng states. + ctx.fwd_cpu_rng_state = torch.get_rng_state() + ctx.fwd_cuda_rng_state = torch.cuda.get_rng_state() + ctx.fwd_cuda_rng_state_tracker = get_cuda_rng_tracker().get_states() + + with torch.no_grad(): + outputs = run_function(*args) + + # Divide hidden states across model parallel group and only keep + # the chunk corresponding to the current rank. + if _CHECKPOINTED_ACTIVATIONS_MEMORY_BUFFER is not None: + ctx.input_0_shape = args[0].data.shape + args[0].data = split_tensor_into_1d_equal_chunks(args[0].data) + args[0].data = _CHECKPOINTED_ACTIVATIONS_MEMORY_BUFFER.add( + args[0].data) + + # Store everything. + ctx.save_for_backward(*args) + + + return outputs + + @staticmethod + def backward(ctx, *args): + if not torch.autograd._is_checkpoint_valid(): + raise RuntimeError("Checkpointing is not compatible with .grad(), " + "please use .backward() if possible") + inputs = ctx.saved_tensors + if _CHECKPOINTED_ACTIVATIONS_MEMORY_BUFFER is not None: + inputs[0].data = gather_split_1d_tensor(inputs[0].data) + inputs[0].data = inputs[0].data.view(ctx.input_0_shape) + + # Store the current states. + bwd_cpu_rng_state = torch.get_rng_state() + bwd_cuda_rng_state = torch.cuda.get_rng_state() + bwd_cuda_rng_state_tracker = get_cuda_rng_tracker().get_states() + + # Set the states to what it used to be before the forward pass. + torch.set_rng_state(ctx.fwd_cpu_rng_state) + _set_cuda_rng_state(ctx.fwd_cuda_rng_state) + get_cuda_rng_tracker().set_states(ctx.fwd_cuda_rng_state_tracker) + + # Compute the forward pass. + detached_inputs = detach_variable(inputs) + with torch.enable_grad(): + outputs = ctx.run_function(*detached_inputs) + + # Set the states back to what it was at the start of this function. + torch.set_rng_state(bwd_cpu_rng_state) + _set_cuda_rng_state(bwd_cuda_rng_state) + get_cuda_rng_tracker().set_states(bwd_cuda_rng_state_tracker) + + if isinstance(outputs, torch.Tensor): + outputs = (outputs,) + torch.autograd.backward(outputs, args) + grads = tuple(inp.grad if isinstance(inp, torch.Tensor) else inp + for inp in detached_inputs) + return (None,) + grads + + +def checkpoint(function, *args): + """Checkpoint a model or part of the model. + This has been directly copied from torch.utils.checkpoint.""" + return CheckpointFunction.apply(function, *args) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/__init__.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/commons.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/commons.py new file mode 100644 index 0000000000000000000000000000000000000000..5e7a186728726517d1b59e1cc861829cbb86f18a --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/commons.py @@ -0,0 +1,83 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os +import random +import numpy +import torch + +import mpu + + +class IdentityLayer(torch.nn.Module): + def __init__(self, size, scale=1.0): + super(IdentityLayer, self).__init__() + self.weight = torch.nn.Parameter(scale * torch.randn(size)) + + def forward(self): + return self.weight + + +def set_random_seed(seed): + """Set random seed for reproducability.""" + random.seed(seed) + numpy.random.seed(seed) + torch.manual_seed(seed) + mpu.model_parallel_cuda_manual_seed(seed) + + +def initialize_distributed(backend='nccl'): + """Initialize torch.distributed.""" + # Get local rank in case it is provided. + parser = argparse.ArgumentParser() + parser.add_argument('--local_rank', type=int, default=None, + help='local rank passed from distributed launcher') + args = parser.parse_args() + local_rank = args.local_rank + + # Get rank and world size. + rank = int(os.getenv('RANK', '0')) + world_size = int(os.getenv("WORLD_SIZE", '1')) + + print('> initializing torch.distributed with local rank: {}, ' + 'rank: {}, world size: {}'.format(local_rank, rank, world_size)) + + # Set the device id. + device = rank % torch.cuda.device_count() + if local_rank is not None: + device = local_rank + torch.cuda.set_device(device) + + # Call the init process. + init_method = 'tcp://' + master_ip = os.getenv('MASTER_ADDR', 'localhost') + master_port = os.getenv('MASTER_PORT', '6000') + init_method += master_ip + ':' + master_port + torch.distributed.init_process_group( + backend=backend, + world_size=world_size, + rank=rank, + init_method=init_method) + + +def print_separator(message): + torch.distributed.barrier() + filler_len = (78 - len(message)) // 2 + filler = '-' * filler_len + string = '\n' + filler + ' {} '.format(message) + filler + if torch.distributed.get_rank() == 0: + print(string, flush=True) + torch.distributed.barrier() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_cross_entropy.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_cross_entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..46d7ba981c906f410e93eddadb2f272e97f5cbb0 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_cross_entropy.py @@ -0,0 +1,108 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from commons import set_random_seed +from commons import IdentityLayer +from commons import print_separator +from commons import initialize_distributed +from mpu.cross_entropy import vocab_parallel_cross_entropy +import mpu +import torch.nn.functional as F +import torch +import random +import sys +sys.path.append("../..") + + +def torch_cross_entropy(batch_size, seq_length, vocab_size, + logits_scale, seed): + set_random_seed(seed) + identity = IdentityLayer((batch_size, seq_length, vocab_size), + scale=logits_scale).cuda() + logits = identity() + target = torch.cuda.LongTensor( + size=(batch_size, seq_length)).random_(0, vocab_size) + loss = F.cross_entropy(logits.view(-1, logits.size()[-1]), + target.view(-1), + reduction='none').view_as(target).mean() + loss.backward() + return loss, identity.weight.grad + + +def mpu_cross_entropy(batch_size, seq_length, vocab_size, + logits_scale, seed): + set_random_seed(seed) + identity = IdentityLayer((batch_size, seq_length, vocab_size), + scale=logits_scale).cuda() + logits = identity() + logits_parallel = mpu.scatter_to_tensor_model_parallel_region(logits) + target = torch.cuda.LongTensor( + size=(batch_size, seq_length)).random_(0, vocab_size) + loss = vocab_parallel_cross_entropy(logits_parallel, target).mean() + loss.backward() + return loss, identity.weight.grad + + +def test_cross_entropy(tensor_model_parallel_size): + + if torch.distributed.get_rank() == 0: + print('> testing cross entropy with model parallel size {} ...'. + format(tensor_model_parallel_size)) + + mpu.initialize_model_parallel(tensor_model_parallel_size) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + batch_size = 13 + seq_length = 17 + vocab_size_per_partition = 11 + logits_scale = 1000.0 + vocab_size = vocab_size_per_partition * tensor_model_parallel_size + seed = 1234 + + loss_torch, grad_torch = torch_cross_entropy(batch_size, seq_length, + vocab_size, logits_scale, + seed) + loss_mpu, grad_mpu = mpu_cross_entropy(batch_size, seq_length, + vocab_size, logits_scale, + seed) + + error = loss_torch.sub_(loss_mpu).abs().max() + print(' max error in loss on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + error = grad_torch.sub_(grad_mpu).abs().max() + print(' max error in grad on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + # Reset groups + mpu.destroy_tensor_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print('>> passed the test :-)') + + +if __name__ == '__main__': + + initialize_distributed() + world_size = torch.distributed.get_world_size() + + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + print_separator('test cross entropy') + test_cross_entropy(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_data.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ae36277036496c3acb9b632aa4e4f9935fe61d18 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_data.py @@ -0,0 +1,88 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from commons import print_separator +from commons import initialize_distributed +from mpu import data as data_utils +import mpu +import torch +import functools +import operator +import sys +sys.path.append("../..") + + +def test_broadcast_data(tensor_model_parallel_size): + + if torch.distributed.get_rank() == 0: + print('> testing broadcast_data with model parallel size {} ...'. + format(tensor_model_parallel_size)) + + mpu.initialize_model_parallel(tensor_model_parallel_size) + torch.manual_seed(1234 + mpu.get_data_parallel_rank()) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + key_size_t = {'key1': [7, 11], + 'key2': [8, 2, 1], + 'key3': [13], + 'key4': [5, 1, 2], + 'key5': [5, 12]} + keys = list(key_size_t.keys()) + + data = {} + data_t = {} + for key in key_size_t: + data[key] = torch.LongTensor(size=key_size_t[key]).random_(0, 1000) + data_t[key] = data[key].clone() + data['keyX'] = torch.FloatTensor(size=(5, )).random_(0, 1000) + data_t['keyX'] = data['keyX'].clone() + if mpu.get_tensor_model_parallel_rank() != 0: + data = None + + data_utils._check_data_types(keys, data_t, torch.int64) + key_size, key_numel, \ + total_numel = data_utils._build_key_size_numel_dictionaries(keys, data) + for key in keys: + assert key_size[key] == key_size_t[key] + total_numel_t = 0 + for key in keys: + target_size = functools.reduce(operator.mul, key_size_t[key], 1) + assert key_numel[key] == target_size + total_numel_t += target_size + assert total_numel == total_numel_t + + data_b = data_utils.broadcast_data(keys, data, torch.int64) + for key in keys: + tensor = data_t[key].cuda() + assert data_b[key].sub(tensor).abs().max() == 0 + + # Reset groups + mpu.destroy_tensor_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print('>> passed the test :-)') + + +if __name__ == '__main__': + + initialize_distributed() + world_size = torch.distributed.get_world_size() + + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + print_separator('test test broadcast data') + test_broadcast_data(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_initialize.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_initialize.py new file mode 100644 index 0000000000000000000000000000000000000000..ba505b8d5c39060a5687654f1a023f2f4527287a --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_initialize.py @@ -0,0 +1,95 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from commons import print_separator +from commons import initialize_distributed +import mpu +import torch +import sys +sys.path.append("../..") + + +def test_initialize_model_parallel(tensor_model_parallel_size): + + if torch.distributed.get_rank() == 0: + print('> testing initialize_model_parallel with size {} ...'.format( + tensor_model_parallel_size)) + tensor_model_parallel_size_ = min(tensor_model_parallel_size, + torch.distributed.get_world_size()) + assert not mpu.model_parallel_is_initialized() + mpu.initialize_model_parallel(tensor_model_parallel_size_) + assert mpu.model_parallel_is_initialized() + + # Checks. + def check(group, world_size, rank): + assert world_size == torch.distributed.get_world_size(group=group) + assert rank == torch.distributed.get_rank(group=group) + + # Model parallel. + world_size = tensor_model_parallel_size_ + rank = torch.distributed.get_rank() % tensor_model_parallel_size_ + assert world_size == mpu.get_tensor_model_parallel_world_size() + assert rank == mpu.get_tensor_model_parallel_rank() + check(mpu.get_tensor_model_parallel_group(), world_size, rank) + + # Data parallel. + world_size = torch.distributed.get_world_size() // tensor_model_parallel_size_ + rank = torch.distributed.get_rank() // tensor_model_parallel_size + assert world_size == mpu.get_data_parallel_world_size() + assert rank == mpu.get_data_parallel_rank() + check(mpu.get_data_parallel_group(), world_size, rank) + + # Reset groups + mpu.destroy_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print('>> passed the test :-)') + + +def test_get_tensor_model_parallel_src_rank(tensor_model_parallel_size_): + + if torch.distributed.get_rank() == 0: + print('> testing get_tensor_model_parallel_src_rank with size {} ...'.format( + tensor_model_parallel_size_)) + tensor_model_parallel_size = min(tensor_model_parallel_size_, + torch.distributed.get_world_size()) + assert not mpu.model_parallel_is_initialized() + mpu.initialize_model_parallel(tensor_model_parallel_size) + assert mpu.model_parallel_is_initialized() + + # Checks + src_rank = torch.distributed.get_rank() - mpu.get_tensor_model_parallel_rank() + assert mpu.get_tensor_model_parallel_src_rank() == src_rank + + # Reset groups + mpu.destroy_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print('>> passed the test :-)') + + +if __name__ == '__main__': + + initialize_distributed() + world_size = torch.distributed.get_world_size() + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + print_separator('test initialize model parallel') + test_initialize_model_parallel(tensor_model_parallel_size) + print_separator('test model parallel source rank') + test_get_tensor_model_parallel_src_rank(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_layers.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..b12f48509bb8f0df75a3b2e02b1230ba1163ef84 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_layers.py @@ -0,0 +1,530 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from mpu import layers +from commons import set_random_seed +from commons import print_separator +from commons import initialize_distributed +import mpu +from torch.nn.parameter import Parameter +import torch.nn.init as init +import torch +import random +import sys +sys.path.append("../..") + + +def test_parallel_embedding(tensor_model_parallel_size): + + if torch.distributed.get_rank() == 0: + print('> testing parallel embedding with model parallel size {} ...'. + format(tensor_model_parallel_size)) + + mpu.initialize_model_parallel(tensor_model_parallel_size) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + batch_size = 17 + seq_length = 23 + vocab_size = 48 + hidden_size = 16 + seed = 1236 + + set_random_seed(123) + input_data = torch.LongTensor( + size=(batch_size, seq_length)).random_(0, vocab_size).cuda() + loss_weight = torch.randn([batch_size, seq_length, hidden_size]).cuda() + + set_random_seed(seed) + embedding_original = torch.nn.Embedding(vocab_size, hidden_size).cuda() + + output = embedding_original(input_data) + loss_original = torch.mul(output, loss_weight).sum() + loss_original.backward() + + set_random_seed(seed) + embedding_parallel = layers.ParallelEmbedding( + vocab_size, hidden_size, init_method=init.normal_).cuda() + output = embedding_parallel(input_data) + loss_parallel = torch.mul(output, loss_weight).sum() + loss_parallel.backward() + + set_random_seed(seed) + embedding_vocab_parallel = layers.VocabParallelEmbedding( + vocab_size, hidden_size, init_method=init.normal_).cuda() + output = embedding_vocab_parallel(input_data) + loss_vocab_parallel = torch.mul(output, loss_weight).sum() + loss_vocab_parallel.backward() + + torch.distributed.barrier() + error = loss_parallel.sub(loss_original).abs() + print(' error in loss (parallel) on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-12, 'error: {}'.format(error) + + torch.distributed.barrier() + error = loss_vocab_parallel.sub(loss_original).abs() + print(' error in loss (vocab parallel) on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-12, 'error: {}'.format(error) + + weight_grad_orig = torch.split(embedding_original.weight.grad, + hidden_size // tensor_model_parallel_size, + 1)[mpu.get_tensor_model_parallel_rank()] + error = embedding_parallel.weight.grad.sub(weight_grad_orig).abs().max() + print(' error in grad (parallel) on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-12, 'error: {}'.format(error) + + weight_grad_orig = torch.split(embedding_original.weight.grad, + vocab_size // tensor_model_parallel_size, + 0)[mpu.get_tensor_model_parallel_rank()] + error = embedding_vocab_parallel.weight.grad.sub( + weight_grad_orig).abs().max() + print(' error in grad (vocab parallel) on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-12, 'error: {}'.format(error) + + # Reset groups + mpu.destroy_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print('>> passed the test :-)') + + +def test_initialize_affine_weight(tensor_model_parallel_size): + + mpu.initialize_model_parallel(tensor_model_parallel_size) + if torch.distributed.get_rank() == 0: + print('> testing initialize_affine_weight with model parallel ' + 'size: {}'.format(tensor_model_parallel_size)) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + seed = 12345 + input_size_coeff = 13 + input_size = input_size_coeff * tensor_model_parallel_size + output_size_coeff = 17 + output_size = output_size_coeff * tensor_model_parallel_size + + # --------------- + # Column parallel + # --------------- + weight = torch.empty(output_size_coeff, input_size) + set_random_seed(seed) + layers._initialize_affine_weight(weight, output_size, input_size, + + output_size_coeff, 0, + torch.nn.init.normal_) + # Target. + set_random_seed(seed) + master_weight = torch.empty(output_size, input_size) + torch.nn.init.normal_(master_weight) + rank = mpu.get_tensor_model_parallel_rank() + my_weight = torch.split(master_weight, output_size_coeff, + dim=0)[rank].contiguous().clone() + + # Compare. + error = weight.sub(my_weight).abs().max() + torch.distributed.barrier() + print(' column parallel max error (should be zero) on global rank ' + '{}: {}'.format(torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + # ------------ + # Row parallel + # ------------ + weight = torch.empty(output_size, input_size_coeff) + set_random_seed(seed) + mpu.layers._initialize_affine_weight(weight, output_size, input_size, + input_size_coeff, 1, + torch.nn.init.normal_) + # Target. + set_random_seed(seed) + master_weight = torch.empty(output_size, input_size) + torch.nn.init.normal_(master_weight) + rank = mpu.get_tensor_model_parallel_rank() + my_weight = torch.split(master_weight, input_size_coeff, + dim=1)[rank].contiguous().clone() + + # Compare. + error = weight.sub(my_weight).abs().max() + torch.distributed.barrier() + print(' row parallel max error (should be zero) on global rank ' + '{}: {}'.format(torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + # Reset groups + mpu.destroy_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print(' >> passed the test :-)') + + +class IdentityLayer2D(torch.nn.Module): + def __init__(self, m, n): + super(IdentityLayer2D, self).__init__() + self.weight = Parameter(torch.Tensor(m, n)) + torch.nn.init.xavier_normal_(self.weight) + + def forward(self): + return self.weight + + +def test_column_parallel_linear(tensor_model_parallel_size): + + mpu.initialize_model_parallel(tensor_model_parallel_size) + if torch.distributed.get_rank() == 0: + print('> testing ColumnParallelLinear with model parallel ' + 'size: {}'.format(tensor_model_parallel_size)) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + seed = 12345 + set_random_seed(seed) + input_size_coeff = 13 + input_size = input_size_coeff * tensor_model_parallel_size + output_size_coeff = 17 + output_size = output_size_coeff * tensor_model_parallel_size + batch_size = 7 + + # Network + identity_layer = IdentityLayer2D(batch_size, input_size).cuda() + linear_layer = mpu.ColumnParallelLinear( + input_size, output_size, keep_master_weight_for_test=True).cuda() + loss_weight = torch.randn([batch_size, output_size]).cuda() + # Forward + input_ = identity_layer() + output = linear_layer(input_) + loss = torch.mul(output, loss_weight).sum() + # Backward + loss.backward() + + # Values. + dLdY = loss_weight + X = identity_layer.weight + A = linear_layer.master_weight.cuda() + dLdA = torch.matmul(dLdY.t(), X) + dLdb = torch.matmul(torch.ones(batch_size, 1).cuda().t(), dLdY).view(-1) + dLdX = torch.matmul(dLdY, A) + + rank = mpu.get_tensor_model_parallel_rank() + my_dLdA = torch.split(dLdA, output_size_coeff, + dim=0)[rank].contiguous().clone() + error = my_dLdA.sub(linear_layer.weight.grad).abs().max() + torch.distributed.barrier() + print(' error in dLdA on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + my_dLdb = torch.split(dLdb, output_size_coeff, + dim=0)[rank].contiguous().clone() + error = my_dLdb.sub(linear_layer.bias.grad).abs().max() + torch.distributed.barrier() + print(' error in dLdb on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + error = dLdX.sub(identity_layer.weight.grad).abs().max() + torch.distributed.barrier() + print(' error in dLdX on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + # Reset groups + mpu.destroy_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print(' >> passed the test :-)') + + +def test_row_parallel_linear(tensor_model_parallel_size): + + mpu.initialize_model_parallel(tensor_model_parallel_size) + if torch.distributed.get_rank() == 0: + print('> testing RowParallelLinear with model parallel ' + 'size: {}'.format(tensor_model_parallel_size)) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + seed = 12345 + set_random_seed(seed) + input_size_coeff = 13 + input_size = input_size_coeff * tensor_model_parallel_size + output_size_coeff = 17 + output_size = output_size_coeff * tensor_model_parallel_size + batch_size = 7 + + # Network + identity_layer = IdentityLayer2D(batch_size, input_size).cuda() + linear_layer = mpu.RowParallelLinear( + input_size, output_size, keep_master_weight_for_test=True).cuda() + loss_weight = torch.randn([batch_size, output_size]).cuda() + # Forward + input_ = identity_layer() + output = linear_layer(input_) + loss = torch.mul(output, loss_weight).sum() + # Backward + loss.backward() + + # Values. + dLdY = loss_weight + X = identity_layer.weight + A = linear_layer.master_weight.cuda() + dLdA = torch.matmul(dLdY.t(), X) + dLdb = torch.matmul(torch.ones(batch_size, 1).cuda().t(), dLdY).view(-1) + dLdX = torch.matmul(dLdY, A) + + rank = mpu.get_tensor_model_parallel_rank() + my_dLdA = torch.split(dLdA, input_size_coeff, + dim=1)[rank].contiguous().clone() + error = my_dLdA.sub(linear_layer.weight.grad).abs().max() + torch.distributed.barrier() + print(' error in dLdA on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + error = dLdb.sub(linear_layer.bias.grad).abs().max() + torch.distributed.barrier() + print(' error in dLdb on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + error = dLdX.sub(identity_layer.weight.grad).abs().max() + torch.distributed.barrier() + print(' error in dLdX on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + # Reset groups + mpu.destroy_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print(' >> passed the test :-)') + + +class IdentityLayer3D(torch.nn.Module): + def __init__(self, m, n, k): + super(IdentityLayer3D, self).__init__() + self.weight = Parameter(torch.Tensor(m, n, k)) + torch.nn.init.xavier_normal_(self.weight) + + def forward(self): + return self.weight + + +def parallel_self_attention(tensor_model_parallel_size, num_att_heads_per_partition, + hidden_size_per_att_head, dropout_prob, batch_size, + sequence_length): + mpu.initialize_model_parallel(tensor_model_parallel_size) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + seed = 12345 + set_random_seed(seed) + + num_att_heads = num_att_heads_per_partition * \ + torch.distributed.get_world_size() + hidden_size = hidden_size_per_att_head * num_att_heads + + # Network + identity_layer = IdentityLayer3D(batch_size, sequence_length, + hidden_size).cuda() + attention_layer = mpu.BertParallelSelfAttention(hidden_size, num_att_heads, + dropout_prob).cuda() + loss_weight = torch.randn([batch_size, sequence_length, hidden_size]).cuda() + attention_mask = torch.randn([batch_size, 1, 1, sequence_length]).cuda() + # Forward + input_ = identity_layer() + output = attention_layer(input_, attention_mask) + loss = torch.mul(output, loss_weight).sum() + # Backward + loss.backward() + + rank = mpu.get_tensor_model_parallel_rank() + mpu.destroy_model_parallel() + return rank, hidden_size, tensor_model_parallel_size, loss, \ + attention_layer, identity_layer + + +def test_parallel_self_attention(tensor_model_parallel_size): + + if torch.distributed.get_rank() == 0: + print('> testing ParallelSelfAttention with model parallel ' + 'size: {}'.format(tensor_model_parallel_size)) + + num_att_heads_per_partition = 3 + hidden_size_per_att_head = 7 + dropout_prob = 0.0 # has to be zero + batch_size = 5 + sequence_length = 13 + + rank_1, hideen_size_1, tensor_model_parallel_size_1, loss_1, \ + attention_layer_1, identity_layer_1 = parallel_self_attention( + 1, num_att_heads_per_partition, + hidden_size_per_att_head, dropout_prob, batch_size, sequence_length) + + rank, hidden_size, tensor_model_parallel_size, loss, \ + attention_layer, identity_layer = parallel_self_attention( + tensor_model_parallel_size, num_att_heads_per_partition, + hidden_size_per_att_head, dropout_prob, batch_size, sequence_length) + assert hideen_size_1 == hidden_size + + error = loss_1.sub(loss).abs().max() + torch.distributed.barrier() + print(' loss error on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 5.0e-6 + + my_lin_grad_list = torch.split( + attention_layer_1.query_key_value.weight.grad, + hidden_size // tensor_model_parallel_size, 0)[rank::tensor_model_parallel_size] + my_lin_grad = torch.cat(my_lin_grad_list, dim=0) + error = my_lin_grad.sub( + attention_layer.query_key_value.weight.grad).abs().max() + torch.distributed.barrier() + print(' weight gradient error on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 5.0e-6 + + error = identity_layer_1.weight.grad.sub( + identity_layer.weight.grad).abs().max() + torch.distributed.barrier() + print(' input gradient error on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 5.0e-6 + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print(' >> passed the test :-)') + + +def parallel_transformer(tensor_model_parallel_size, num_att_heads_per_partition, + hidden_size_per_att_head, batch_size, sequence_length): + + mpu.initialize_model_parallel(tensor_model_parallel_size) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + seed = 12345 + set_random_seed(seed) + + num_att_heads = num_att_heads_per_partition * \ + torch.distributed.get_world_size() + hidden_size = hidden_size_per_att_head * num_att_heads + intermediate_size = 4 * hidden_size + + # Network + identity_layer = IdentityLayer3D(batch_size, sequence_length, + hidden_size).cuda() + transformer_layer = mpu.BertParallelTransformerLayer( + hidden_size, intermediate_size, num_att_heads, 0.0, 0.0, + torch.nn.functional.relu, 1.0e-5).cuda() + + loss_weight = torch.randn([batch_size, sequence_length, hidden_size]).cuda() + attention_mask = torch.randn([batch_size, 1, 1, sequence_length]).cuda() + # Forward + input_ = identity_layer() + output = transformer_layer(input_, attention_mask) + loss = torch.mul(output, loss_weight).sum() + # Backward + loss.backward() + + rank = mpu.get_tensor_model_parallel_rank() + mpu.destroy_model_parallel() + return rank, hidden_size, tensor_model_parallel_size, loss, \ + transformer_layer, identity_layer + + +def test_parallel_transformer_layer(tensor_model_parallel_size): + + if torch.distributed.get_rank() == 0: + print('> testing ParallelTransformerLayer with model parallel ' + 'size: {}'.format(tensor_model_parallel_size)) + + num_att_heads_per_partition = 3 + hidden_size_per_att_head = 7 + batch_size = 5 + sequence_length = 13 + + rank_1, hidden_size_1, tensor_model_parallel_size_1, loss_1, \ + transformer_layer_1, identity_layer_1 = parallel_transformer( + 1, num_att_heads_per_partition, + hidden_size_per_att_head, batch_size, sequence_length) + + rank, hidden_size, tensor_model_parallel_size, loss, \ + transformer_layer, identity_layer = parallel_transformer( + tensor_model_parallel_size, num_att_heads_per_partition, + hidden_size_per_att_head, batch_size, sequence_length) + + error = loss_1.sub(loss).abs().max() + torch.distributed.barrier() + print(' loss error on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 5.0e-5, 'error: {}'.format(error) + + error = identity_layer_1.weight.grad.sub( + identity_layer.weight.grad).abs().max() + torch.distributed.barrier() + print(' input gradient error on global rank {}: {}'.format( + torch.distributed.get_rank(), error)) + assert error < 5.0e-5, 'error: {}'.format(error) + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print(' >> passed the test :-)') + + +if __name__ == '__main__': + + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + initialize_distributed() + world_size = torch.distributed.get_world_size() + + print_separator('test initialize affine weight') + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + test_initialize_affine_weight(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 + + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + print_separator('test parallel embedding') + test_parallel_embedding(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 + + print_separator('test column-parallel linear') + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + test_column_parallel_linear(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 + + print_separator('test row-parallel linear') + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + test_row_parallel_linear(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 + + print_separator('test parallel self-attention') + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + test_parallel_self_attention(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 + + print_separator('test parallel transformer') + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + test_parallel_transformer_layer(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_random.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_random.py new file mode 100644 index 0000000000000000000000000000000000000000..9c9c503410f7f3bd790b0b55a8cca696fc55097d --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/tests/test_random.py @@ -0,0 +1,204 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from commons import print_separator +from commons import initialize_distributed +import mpu +import torch +import sys +sys.path.append("../..") + + +def test_set_cuda_rng_state(tensor_model_parallel_size): + + if torch.distributed.get_rank() == 0: + print('> testing set_rng_state with size {} ...'. + format(tensor_model_parallel_size)) + + mpu.initialize_model_parallel(tensor_model_parallel_size) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + size = 123 + seed = 1234 + torch.cuda.manual_seed(1234) + tensor = torch.cuda.FloatTensor(size) + + # Get the state + rng_state = torch.cuda.get_rng_state() + rng_state_copy = rng_state.clone() + + # Do some stuff. + for _ in range(5): + torch.randn(size, out=tensor) + result_1 = tensor.clone() + + assert rng_state.sub(rng_state_copy).max() == 0 + assert torch.cuda.get_rng_state().sub(rng_state_copy).max() > 0 + + # State should be different. + new_rng_state = torch.cuda.get_rng_state() + max_diff = new_rng_state.sub(rng_state).max() + print(' max diff in rng state (should be non-zero) on global rank {}: {}'. + format(torch.distributed.get_rank(), max_diff)) + assert max_diff > 0 + + # Reset the rng state and do the same stuff. + mpu.random._set_cuda_rng_state(rng_state) + for _ in range(5): + torch.randn(size, out=tensor) + mpu.random._set_cuda_rng_state(rng_state) + for _ in range(5): + torch.randn(size, out=tensor) + result_2 = tensor.clone() + + # Results should be the same + error = result_2.sub(result_1).abs().max() + print(' max error in generated tensors (should be zero) on ' + 'global rank {}: {}'.format(torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + # Input state should have remained intact. + error = rng_state.sub(rng_state_copy).max() + print(' max error in rng state (should be zero) on global rank {}: {}'. + format(torch.distributed.get_rank(), error)) + assert error == 0 + + # Reset groups + mpu.destroy_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print('>> passed the test :-)') + + +def test_cuda_rng_tracker(tensor_model_parallel_size): + + if torch.distributed.get_rank() == 0: + print('> testing cuda rng tracker with size {} ...'. + format(tensor_model_parallel_size)) + + mpu.initialize_model_parallel(tensor_model_parallel_size) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + seed_1 = 1234 + seed_2 = 4321 + size = [12, 21] + tensor = torch.cuda.FloatTensor(size) + + # Set to seed_1 and generate two tensors. + torch.cuda.manual_seed(seed_1) + torch.randn(size, out=tensor) + target_11 = tensor.clone() + torch.randn(size, out=tensor) + target_12 = tensor.clone() + + # Set to seed_2 and generate two tensors. + torch.cuda.manual_seed(seed_2) + torch.randn(size, out=tensor) + target_21 = tensor.clone() + torch.randn(size, out=tensor) + target_22 = tensor.clone() + + # Now if we interleave seed_1 and seed_2, + # we should still get the same tensors + torch.cuda.manual_seed(seed_1) + mpu.get_cuda_rng_tracker().add('test', seed_2) + + torch.randn(size, out=tensor) + result_11 = tensor.clone() + + with mpu.get_cuda_rng_tracker().fork('test'): + torch.randn(size, out=tensor) + result_21 = tensor.clone() + + torch.randn(size, out=tensor) + result_12 = tensor.clone() + + with mpu.get_cuda_rng_tracker().fork('test'): + torch.randn(size, out=tensor) + result_22 = tensor.clone() + + diff = result_11.sub(result_21).abs().max() + diff = min(diff, result_12.sub(result_22).abs().max()) + print(' max diff in generated tensors (should be non-zero) on ' + 'global rank {}: {}'.format(torch.distributed.get_rank(), diff)) + assert diff > 1.0e-6 + error = max(result_11.sub(target_11).abs().max(), + result_12.sub(target_12).abs().max()) + error = max(error, result_21.sub(target_21).abs().max()) + error = max(error, result_22.sub(target_22).abs().max()) + print(' max error in generated tensors (should be zero) on ' + 'global rank {}: {}'.format(torch.distributed.get_rank(), error)) + assert error < 1.0e-6 + + # Reset the tracker + mpu.get_cuda_rng_tracker().reset() + + # Reset groups + mpu.destroy_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print('>> passed the test :-)') + + +def test_model_parallel_cuda_manual_seed(tensor_model_parallel_size): + + if torch.distributed.get_rank() == 0: + print('> testing model parallel cuda manual seed with size {} ...'. + format(tensor_model_parallel_size)) + + mpu.initialize_model_parallel(tensor_model_parallel_size) + tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size() + + mpu.model_parallel_cuda_manual_seed(12345) + assert torch.cuda.initial_seed() == 12345 + with mpu.get_cuda_rng_tracker().fork(): + assert torch.cuda.initial_seed() == (12345 + 2718 + + mpu.get_tensor_model_parallel_rank()) + + # Reset the tracker + mpu.get_cuda_rng_tracker().reset() + + # Reset groups + mpu.destroy_model_parallel() + + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + print('>> passed the test :-)') + + +if __name__ == '__main__': + + initialize_distributed() + world_size = torch.distributed.get_world_size() + + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + print_separator('test set rng state') + test_set_cuda_rng_state(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 + + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + print_separator('test cuda rng tracker') + test_cuda_rng_tracker(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 + + tensor_model_parallel_size = 1 + while tensor_model_parallel_size <= world_size: + print_separator('test model parallel cuda manual seed') + test_model_parallel_cuda_manual_seed(tensor_model_parallel_size) + tensor_model_parallel_size *= 2 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/utils.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..81339ecd74f1d787e4ec5c412e6dd688415b8dbf --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/mpu/utils.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import torch + + +def ensure_divisibility(numerator, denominator): + """Ensure that numerator is divisible by the denominator.""" + assert numerator % denominator == 0, '{} is not divisible by {}'.format( + numerator, denominator) + + +def divide(numerator, denominator): + """Ensure that numerator is divisible by the denominator and return + the division value.""" + ensure_divisibility(numerator, denominator) + return numerator // denominator + + +def split_tensor_along_last_dim(tensor, num_partitions, + contiguous_split_chunks=False): + """Split a tensor along its last dimension. + Arguments: + tensor: input tensor. + num_partitions: number of partitions to split the tensor + contiguous_split_chunks: If True, make each chunk contiguous + in memory. + """ + # Get the size and dimension. + last_dim = tensor.dim() - 1 + last_dim_size = divide(tensor.size()[last_dim], num_partitions) + # Split. + tensor_list = torch.split(tensor, last_dim_size, dim=last_dim) + # Note: torch.split does not create contiguous tensors by default. + if contiguous_split_chunks: + return tuple(chunk.contiguous() for chunk in tensor_list) + + return tensor_list + + +class VocabUtility: + """Split the vocabulary into `world_size` chunks amd return the + first and last index of the vocabulary belonging to the `rank` + partition: Note that indecies in [fist, last)""" + + @staticmethod + def vocab_range_from_per_partition_vocab_size(per_partition_vocab_size, + rank, world_size): + index_f = rank * per_partition_vocab_size + index_l = index_f + per_partition_vocab_size + return index_f, index_l + + @staticmethod + def vocab_range_from_global_vocab_size(global_vocab_size, rank, world_size): + per_partition_vocab_size = divide(global_vocab_size, world_size) + return VocabUtility.vocab_range_from_per_partition_vocab_size( + per_partition_vocab_size, rank, world_size) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/__init__.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..78bd941d1769a65ce6f8ca9e364140402f16ca30 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/__init__.py @@ -0,0 +1,159 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +if torch.cuda.is_available(): + from apex.optimizers import FusedAdam as Adam + from apex.optimizers import FusedSGD as SGD +else: + #TODO: SW-90304 enable fused adam + from torch.optim import Adam + from torch.optim import SGD + +from torch.optim import AdamW + +from megatron import get_args +from megatron.model import LayerNorm, RMSNorm + +from .grad_scaler import ConstantGradScaler, DynamicGradScaler +from .optimizer import Float16OptimizerWithFloat16Params, FP32Optimizer + +def _get_params_for_weight_decay_optimization(modules): + """Divide params into with-weight-decay and without-weight-decay groups. + Layernorms and baises will have no weight decay but the rest will. + """ + args = get_args() + + weight_decay_params = {'params': [], 'name' : 'weight_decay_params'} + no_weight_decay_params = {'params': [], 'weight_decay': 0.0, 'name': 'no_weight_decay_params'} + + for module in modules: + for module_ in module.modules(): + if isinstance(module_, LayerNorm) or isinstance(module_, RMSNorm): + if args.do_layernorm_bias_weight_decay: + weight_decay_params['params'].extend( + [p for n, p in list(module_._parameters.items()) + if p is not None]) + else: + no_weight_decay_params['params'].extend( + [p for p in list(module_._parameters.values()) + if p is not None]) + else: + if args.do_layernorm_bias_weight_decay: + weight_decay_params['params'].extend( + [p for n, p in list(module_._parameters.items()) + if p is not None]) + else: + weight_decay_params['params'].extend( + [p for n, p in list(module_._parameters.items()) + if p is not None and n != 'bias']) + no_weight_decay_params['params'].extend( + [p for n, p in list(module_._parameters.items()) + if p is not None and n == 'bias']) + return weight_decay_params, no_weight_decay_params + +def get_megatron_optimizer(model): + args = get_args() + + # Base optimizer. + param_groups = _get_params_for_weight_decay_optimization(model) + if args.create_moe_param_group: + from deepspeed.moe.utils import is_moe_param, split_params_into_different_moe_groups_for_optimizer + param_groups = split_params_into_different_moe_groups_for_optimizer(param_groups) + + if args.cpu_optimizer: + assert args.optimizer == 'adam', 'CPU offloading is for Adam' + if args.cpu_torch_adam: + cpu_adam_optimizer = torch.optim.AdamW + else: + from deepspeed.ops.adam import DeepSpeedCPUAdam + cpu_adam_optimizer = DeepSpeedCPUAdam + optimizer = cpu_adam_optimizer(param_groups, + lr=args.lr, + weight_decay=args.weight_decay) + else: + if args.optimizer == 'adamw': + optimizer = AdamW(param_groups, + lr=args.lr, + weight_decay=args.weight_decay, + betas=(args.adam_beta1, args.adam_beta2), + eps=args.adam_eps) + elif args.optimizer == 'fusedadamw': + assert args.use_hpu, "FusedAdamW optimizer is supported only when using HPU" + from habana_frameworks.torch.hpex.optimizers import FusedAdamW + optimizer = FusedAdamW(param_groups, + lr=args.lr, + weight_decay=args.weight_decay, + betas=(args.adam_beta1, args.adam_beta2), + eps=args.adam_eps) + elif args.optimizer == 'adam': + optimizer = Adam(param_groups, + lr=args.lr, + weight_decay=args.weight_decay, + betas=(args.adam_beta1, args.adam_beta2), + eps=args.adam_eps) + elif args.optimizer == 'sgd': + optimizer = SGD(param_groups, + lr=args.lr, + weight_decay=args.weight_decay, + momentum=args.sgd_momentum) + else: + raise Exception('{} optimizer is not supported.'.format( + args.optimizer)) + + if args.deepspeed: + return optimizer + + # Determine whether the params have main-grad field. + params_have_main_grad = False + if args.DDP_impl == 'local': + params_have_main_grad = True + + if args.fp16 or args.bf16: + + # Grad scaler: + # if loss-scale is provided, instantiate the constant scaler. + # if we are using fp16 and loss-scale is not present, use a + # dynamic scaler. + # otherwise we are running in bf16 with no loss-scale so + # leave it as None. + grad_scaler = None + # Constant loss scale. + if args.loss_scale: + grad_scaler = ConstantGradScaler(args.loss_scale) + # Dynamic loss scale. + else: + if args.fp16: + grad_scaler = DynamicGradScaler( + initial_scale=args.initial_loss_scale, + min_scale=args.min_loss_scale, + growth_factor=2.0, + backoff_factor=0.5, + growth_interval=args.loss_scale_window, + hysteresis=args.hysteresis) + + # Megatron optimizer. + return Float16OptimizerWithFloat16Params(optimizer, + args.clip_grad, + args.log_num_zeros_in_grad, + params_have_main_grad, + args.bf16, + grad_scaler) + + # FP32. + return FP32Optimizer(optimizer, args.clip_grad, + args.log_num_zeros_in_grad, + params_have_main_grad) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/clip_grads.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/clip_grads.py new file mode 100644 index 0000000000000000000000000000000000000000..79ab4092ec52f0d8e9f91565ab7703d2544202e1 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/clip_grads.py @@ -0,0 +1,157 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Gradient clipping.""" + +import torch +from torch import inf +from megatron import get_args + +if (torch.cuda.is_available()): + from apex.multi_tensor_apply import multi_tensor_applier + import amp_C + +from megatron import mpu +from megatron.model.module import param_is_not_shared +from megatron.mpu.layers import param_is_not_tensor_parallel_duplicate + + +def clip_grad_norm_fp32(parameters, max_norm, norm_type=2): + """Clips gradient norm of an iterable of parameters whose gradients + are in fp32. + + This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and + added functionality to handle model parallel parameters. Note that + the gradients are modified in place. + + Arguments: + parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a + single Tensor that will have gradients normalized + max_norm (float or int): max norm of the gradients + norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for + infinity norm. + + Returns: + Total norm of the parameters (viewed as a single vector). + """ + + if isinstance(parameters, torch.Tensor): + parameters = [parameters] + + # Filter parameters based on: + # - grad should not be none + # - parameter should not be shared + # - should not be a replica due to tensor model parallelism + grads = [] + grads_for_norm = [] + for param in parameters: + grad_not_none = param.grad is not None + is_not_shared = param_is_not_shared(param) + is_not_tp_duplicate = param_is_not_tensor_parallel_duplicate(param) + grad = param.grad.detach() + if grad_not_none: + # Make sure the grads are in fp32 + assert param.grad.dtype == torch.float32 + grads.append(grad) + if grad_not_none and is_not_shared and is_not_tp_duplicate: + grads_for_norm.append(grad) + + # Norm parameters. + max_norm = float(max_norm) + norm_type = float(norm_type) + total_norm = 0.0 + + args = get_args() + # Calculate norm. + if norm_type == inf: + total_norm = max(grad.abs().max() for grad in grads_for_norm) + total_norm_cuda = torch.cuda.FloatTensor([float(total_norm)]).to(args.device) + # Take max across all model-parallel GPUs. + torch.distributed.all_reduce(total_norm_cuda, + op=torch.distributed.ReduceOp.MAX, + group=mpu.get_model_parallel_group()) + total_norm = total_norm_cuda[0].item() + + else: + # TODO SW-56092: not having multi_tensor_applier implementation outside CUDA + if args.device.type == "cuda" and norm_type == 2.0: + dummy_overflow_buf = torch.cuda.IntTensor([0]) + # Use apex's multi-tensor applier for efficiency reasons. + # Multi-tensor applier takes a function and a list of list + # and performs the operation on that list all in one kernel. + grad_norm, _ = multi_tensor_applier( + amp_C.multi_tensor_l2norm, + dummy_overflow_buf, + [grads_for_norm], + False # no per-parameter norm + ) + # Since we will be summing across data parallel groups, + # we need the pow(norm-type). + total_norm = grad_norm ** norm_type + + else: + for grad in grads_for_norm: + grad_norm = torch.norm(grad, norm_type) + total_norm += grad_norm ** norm_type + + # Sum across all model-parallel GPUs. + torch.distributed.all_reduce(total_norm, + op=torch.distributed.ReduceOp.SUM, + group=mpu.get_model_parallel_group()) + total_norm = total_norm.item() ** (1.0 / norm_type) + + # Scale. + clip_coeff = max_norm / (total_norm + 1.0e-6) + if clip_coeff < 1.0: + if args.device.type == "cuda": + dummy_overflow_buf = torch.cuda.IntTensor([0]) + multi_tensor_applier(amp_C.multi_tensor_scale, + dummy_overflow_buf, + [grads, grads], + clip_coeff) + else: + for grad in grads: # NadavE GalH check if need to detach gradients. + grad.mul_(clip_coeff) + + return total_norm + + +def count_zeros_fp32(parameters): + + if isinstance(parameters, torch.Tensor): + parameters = [parameters] + + # Filter parameters based on: + # - grad should not be none + # - parameter should not be shared + # - should not be a replica due to tensor model parallelism + total_num_zeros = 0.0 + for param in parameters: + grad_not_none = param.grad is not None + is_not_shared = param_is_not_shared(param) + is_not_tp_duplicate = param_is_not_tensor_parallel_duplicate(param) + if grad_not_none and is_not_shared and is_not_tp_duplicate: + grad = param.grad.detach() + num_zeros = grad.numel() - torch.count_nonzero(grad) + total_num_zeros = num_zeros + total_num_zeros + + # Sum across all model-parallel GPUs. + torch.distributed.all_reduce(total_num_zeros, + op=torch.distributed.ReduceOp.SUM, + group=mpu.get_model_parallel_group()) + total_num_zeros = total_num_zeros.item() + + return total_num_zeros diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/grad_scaler.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/grad_scaler.py new file mode 100644 index 0000000000000000000000000000000000000000..6b25588db7a7366ec0e7f9930d8fda773b0f91a9 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/grad_scaler.py @@ -0,0 +1,133 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Megatron grad scaler.""" + +from abc import ABC +from abc import abstractmethod + +import torch + + +class MegatronGradScaler(ABC): + + def __init__(self, initial_scale): + """Initialize scale value with the input initial scale.""" + assert initial_scale > 0.0 + self._scale = torch.cuda.FloatTensor([initial_scale]) + + @property + def scale(self): + return self._scale + + @property + def inv_scale(self): + return self._scale.double().reciprocal().float() + + @abstractmethod + def update(self, found_inf): + pass + + @abstractmethod + def state_dict(self): + pass + + @abstractmethod + def load_state_dict(self, state_dict): + pass + + + +class ConstantGradScaler(MegatronGradScaler): + + def update(self, found_inf): + pass + + def state_dict(self): + return dict() + + def load_state_dict(self, state_dict): + pass + + + +class DynamicGradScaler(MegatronGradScaler): + + def __init__(self, initial_scale, min_scale, + growth_factor, backoff_factor, + growth_interval, hysteresis): + """"Grad scaler with dynamic scale that gets adjusted + during training.""" + super(DynamicGradScaler, self).__init__(initial_scale) + + # Lower bound on the scale. + assert min_scale > 0.0 + assert min_scale <= initial_scale + self.min_scale = torch.cuda.FloatTensor([min_scale]) + # Growth and backoff factors for the scale. + assert growth_factor > 1.0 + self.growth_factor = torch.cuda.FloatTensor([growth_factor]) + assert backoff_factor < 1.0 + assert backoff_factor > 0.0 + self.backoff_factor = torch.cuda.FloatTensor([backoff_factor]) + # Interval over which if we don't see any inf/nan, + # we will scale the grad scale by the growth factor. + assert growth_interval > 0 + self.growth_interval = growth_interval + # Number of inf/nans we should see before scaling down + # the grad scale by the backoff factor. + assert hysteresis > 0 + self.hysteresis = hysteresis + + # Trackers. + self._growth_tracker = 0 + self._hysteresis_tracker = self.hysteresis + + + def update(self, found_inf): + + # If we have an inf/nan, growth tracker is set to 0 + # and hysterisis tracker is reduced by 1. + if found_inf: + self._growth_tracker = 0 + self._hysteresis_tracker -= 1 + # Now if we are out of hysteresis count, scale down the loss. + if self._hysteresis_tracker <= 0: + self._scale = torch.max(self._scale * self.backoff_factor, + self.min_scale) + else: + # If there is no nan/inf, increment the growth tracker. + self._growth_tracker += 1 + # If we have had enough consequitive intervals with no nan/inf: + if self._growth_tracker == self.growth_interval: + # Reset the tracker and hysteresis trackers, + self._growth_tracker = 0 + self._hysteresis_tracker = self.hysteresis + # and scale up the loss scale. + self._scale = self._scale * self.growth_factor + + + def state_dict(self): + state_dict = {} + state_dict['scale'] = self._scale + state_dict['growth_tracker'] = self._growth_tracker + state_dict['hysteresis_tracker'] = self._hysteresis_tracker + return state_dict + + + def load_state_dict(self, state_dict): + self._scale = state_dict['scale'].cuda(torch.cuda.current_device()) + self._growth_tracker = state_dict['growth_tracker'] + self._hysteresis_tracker = state_dict['hysteresis_tracker'] diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/optimizer.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..77f69858c0b49d64a733fc0d06f1236c8c046853 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/optimizer/optimizer.py @@ -0,0 +1,527 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Megatron optimizer.""" + +from abc import ABC +from abc import abstractmethod +from megatron.global_vars import get_current_device + +import torch + +if (torch.cuda.is_available()): + from apex.multi_tensor_apply import multi_tensor_applier + import amp_C + +from megatron import get_timers, get_args +from megatron import mpu +from megatron import print_rank_0 + +from .clip_grads import clip_grad_norm_fp32, count_zeros_fp32 + + +def _zero_grad_group_helper(group, set_to_none): + """Zero out the gradient for a group of parameters. + Note: copied from torch.optim.optimizer.""" + for param in group: + if param.grad is not None: + if set_to_none: + param.grad = None + else: + if param.grad.grad_fn is not None: + param.grad.detach_() + else: + param.grad.requires_grad_(False) + param.grad.zero_() + + +def _multi_tensor_copy_this_to_that(this, that, overflow_buf=None): + """Use multi-tensor-applier to copy values from one list to another. + We don't have a blfoat16 implementation so for now if the overflow_buf + is not provided, we default back to simple loop copy to be compatible + with bfloat16.""" + # TODO SW-56092: not having multi_tensor_applier implementation outside CUDA + if get_args().device.type == "cuda" and overflow_buf: + overflow_buf.fill_(0) + # Scaling with factor `1.0` is equivalent to copy. + multi_tensor_applier(amp_C.multi_tensor_scale, + overflow_buf, + [this, that], + 1.0) + else: + for this_, that_ in zip(this, that): + that_.copy_(this_) + + + +class MegatronOptimizer(ABC): + + + def __init__(self, optimizer, clip_grad, + log_num_zeros_in_grad, + params_have_main_grad): + """Input optimizer is the base optimizer for example Adam.""" + self.optimizer = optimizer + assert self.optimizer, 'no optimizer is provided.' + # Set gradient clipping and logging params. + self.clip_grad = clip_grad + self.log_num_zeros_in_grad = log_num_zeros_in_grad + self.params_have_main_grad = params_have_main_grad + + + def get_parameters(self): + params = [] + for param_group in self.optimizer.param_groups: + for param in param_group['params']: + params.append(param) + return params + + + def clip_grad_norm(self, clip_grad): + params = self.get_parameters() + return clip_grad_norm_fp32(params, clip_grad) + + + def count_zeros(self): + params = self.get_parameters() + return count_zeros_fp32(params) + + + @abstractmethod + def zero_grad(self, set_to_none=True): + pass + + + @abstractmethod + def get_loss_scale(self): + """The output should be a cuda tensor of size 1.""" + pass + + + def scale_loss(self, loss): + """Simple scaling.""" + return self.get_loss_scale() * loss + + + @abstractmethod + def step(self): + pass + + + @abstractmethod + def reload_model_params(self): + """Refreshes any internal state from the current model parameters. + Call whenever the parameters are changed outside of the optimizer. + For example, when we load a model from a checkpoint without loading + the optimizer, the model parameters are updated but for fp16 optimizer + with main parameters, the main parameters need to also be updated.""" + pass + + + @abstractmethod + def state_dict(self): + pass + + + @abstractmethod + def load_state_dict(self, state_dict): + pass + + + # Promote state so it can be retrieved or set via + # "optimizer_instance.state" + def _get_state(self): + return self.optimizer.state + + def _set_state(self, value): + self.optimizer.state = value + + state = property(_get_state, _set_state) + + + # Promote param_groups so it can be retrieved or set via + # "optimizer_instance.param_groups" + # (for example, to adjust the learning rate) + def _get_param_groups(self): + return self.optimizer.param_groups + + def _set_param_groups(self, value): + self.optimizer.param_groups = value + + param_groups = property(_get_param_groups, _set_param_groups) + + + +class Float16OptimizerWithFloat16Params(MegatronOptimizer): + """Float16 optimizer for fp16 and bf16 data types. + + Arguments: + optimizer: base optimizer such as Adam or SGD + clip_grad: clip gradeints with this global L2 norm. Note + that clipping is ignored if clip_grad == 0 + log_num_zeros_in_grad: return number of zeros in the gradients. + params_have_main_grad: flag indicating if parameters have + a `main_grad` field. If this is set, we are assuming + that the model parameters are store in the `main_grad` + field instead of the typical `grad` field. This happens + for the DDP cases where there is a contihuous buffer + holding the gradients. For example for bfloat16, we want + to do gradient accumulation and all-reduces in float32 + and as a result we store those gradients in the main_grad. + Note that main grad is not necessarily in float32. + bf16: if true, the model is running in bfloat16. + grad_scaler: used for scaling gradients. Note that this can be + None. This case happens when `bf16 = True` and we don't + use any loss scale. Note that for `bf16 = True`, we can have + a constnat gradient scaler. Also for `bf16 = False`, we + always require a grad scaler. + """ + + def __init__(self, optimizer, clip_grad, log_num_zeros_in_grad, + params_have_main_grad, bf16, grad_scaler): + + super(Float16OptimizerWithFloat16Params, self).__init__( + optimizer, clip_grad, log_num_zeros_in_grad, + params_have_main_grad) + + self.bf16 = bf16 + self.grad_scaler = grad_scaler + # None grad scaler is only supported for bf16. + if self.grad_scaler is None: + assert self.bf16, 'fp16 expects a grad scaler.' + + # Tensor used to determine if a nan/if has happend. + # Any non-zero value indicates inf/nan. + # Note that we keep this for the cases that grad scaler is none. + # We still record nan/inf if we have a bfloat16 with a grad scaler. + if self.grad_scaler: + self.found_inf = torch.cuda.FloatTensor([0.0]) + + # Dummy tensor needed for apex multi-apply tensor. + # For bfloat, we don't have multi-tensor apply and for now + # we set it to none so the multi-tensor apply gets ignored. + if bf16: + self._dummy_overflow_buf = None + else: + self._dummy_overflow_buf = torch.cuda.IntTensor([0]) + + # In case grad scaler is not passed, define the unity scale. + if self.grad_scaler is None: + self._scale_one = torch.cuda.FloatTensor([1.0]) + + # ====================== + # main parameter stuff + # ====================== + + # Three groups of parameters: + # float16_groups: original float16 parameters + # fp32_from_float16_groups: fp32 copy of float16 parameters + # fp32_from_fp32_groups: original fp32 parameters + self.float16_groups = [] + self.fp32_from_float16_groups = [] + self.fp32_from_fp32_groups = [] + + # For all the groups in the original optimizer: + for param_group in self.optimizer.param_groups: + float16_params_this_group = [] + fp32_params_this_group = [] + fp32_from_float16_params_this_group = [] + # For all the parameters in this group: + for i, param in enumerate(param_group['params']): + if param.requires_grad: + + # float16 params: + if param.type() in ['torch.cuda.HalfTensor', + 'torch.cuda.BFloat16Tensor']: + float16_params_this_group.append(param) + # Create a copy + main_param = param.detach().clone().float() + # Copy tensor model parallel attributes. + mpu.copy_tensor_model_parallel_attributes(main_param, + param) + if hasattr(param, 'shared'): + main_param.shared = param.shared + # Replace the optimizer params with the new fp32 copy. + param_group['params'][i] = main_param + fp32_from_float16_params_this_group.append(main_param) + # Reset existing state dict key to the new main param. + if param in self.optimizer.state: + self.optimizer.state[main_param] \ + = self.optimizer.state.pop(param) + + # fp32 params. + elif param.type() == 'torch.cuda.FloatTensor': + fp32_params_this_group.append(param) + param_group['params'][i] = param + + else: + raise TypeError('Wrapped parameters must be one of ' + 'torch.cuda.FloatTensor, ' + 'torch.cuda.HalfTensor, or ' + 'torch.cuda.BFloat16Tensor. ' + 'Received {}'.format(param.type())) + + self.float16_groups.append(float16_params_this_group) + self.fp32_from_float16_groups.append( + fp32_from_float16_params_this_group) + self.fp32_from_fp32_groups.append(fp32_params_this_group) + + # Leverage state_dict() and load_state_dict() to + # recast preexisting per-param state tensors + self.optimizer.load_state_dict(self.optimizer.state_dict()) + + + def zero_grad(self, set_to_none=True): + """We only need to zero the model related parameters, i.e., + float16_groups & fp32_from_fp32_groups.""" + for group in self.float16_groups: + _zero_grad_group_helper(group, set_to_none) + for group in self.fp32_from_fp32_groups: + _zero_grad_group_helper(group, set_to_none) + + + def get_loss_scale(self): + if self.grad_scaler is None: + return self._scale_one + return self.grad_scaler.scale + + + def _copy_model_grads_to_main_grads(self): + # This only needs to be done for the float16 group. + for model_group, main_group in zip(self.float16_groups, + self.fp32_from_float16_groups): + for model_param, main_param in zip(model_group, main_group): + if self.params_have_main_grad: + main_param.grad = model_param.main_grad.float() + else: + if model_param.grad is not None: + main_param.grad = model_param.grad.float() + # For fp32 grads, we need to reset the grads to main grad. + if self.params_have_main_grad: + for model_group in self.fp32_from_fp32_groups: + for model_param in model_group: + model_param.grad = model_param.main_grad + + + def _unscale_main_grads_and_check_for_nan(self): + main_grads = [] + # fp32 params fromm float16 ones. + for main_group in self.fp32_from_float16_groups: + for main_param in main_group: + if main_param.grad is not None: + main_grads.append(main_param.grad.data) + # Append fp32 parameters. + for main_group in self.fp32_from_fp32_groups: + for main_param in main_group: + if main_param.grad is not None: + main_grads.append(main_param.grad.data) + # Reset found inf. + self.found_inf.fill_(0.0) + # Unscale and set found inf/nan + torch._amp_foreach_non_finite_check_and_unscale_( + main_grads, self.found_inf, self.grad_scaler.inv_scale) + # Update across all model parallel instances. + torch.distributed.all_reduce(self.found_inf, + op=torch.distributed.ReduceOp.MAX, + group=mpu.get_model_parallel_group()) + + # Check for nan. + found_inf_flag = (self.found_inf.item() > 0) + return found_inf_flag + + + def _get_model_and_main_params_data_float16(self): + model_data = [] + main_data = [] + for model_group, main_group in zip(self.float16_groups, + self.fp32_from_float16_groups): + for model_param, main_param in zip(model_group, main_group): + model_data.append(model_param.data) + main_data.append(main_param.data) + return model_data, main_data + + + def _copy_main_params_to_model_params(self): + # Only needed for the float16 params. + model_data, main_data = self._get_model_and_main_params_data_float16() + _multi_tensor_copy_this_to_that(this=main_data, that=model_data, + overflow_buf=self._dummy_overflow_buf) + + + def _copy_model_params_to_main_params(self): + # Only needed for the float16 params. + model_data, main_data = self._get_model_and_main_params_data_float16() + _multi_tensor_copy_this_to_that(this=model_data, that=main_data, + overflow_buf=self._dummy_overflow_buf) + + + def reload_model_params(self): + self._copy_model_params_to_main_params() + + + @torch.no_grad() + def step(self): + + timers = get_timers() + + # Copy gradients from model params to main params. + timers('optimizer-copy-to-main-grad').start() + self._copy_model_grads_to_main_grads() + timers('optimizer-copy-to-main-grad').stop() + + # Do unscale, check for inf, and update grad scaler only for + # the case that grad scaler is provided. + if self.grad_scaler: + + # Unscale and check for inf/nan. + timers('optimizer-unscale-and-check-inf').start() + found_inf_flag = self._unscale_main_grads_and_check_for_nan() + timers('optimizer-unscale-and-check-inf').stop() + + # We are done with scaling gradients + # so we can update the loss scale. + self.grad_scaler.update(found_inf_flag) + + # If we found inf/nan, skip the update. + if found_inf_flag: + return False, None, None + + # Clip the main gradients. + timers('optimizer-clip-main-grad').start() + grad_norm = None + if self.clip_grad > 0.0: + grad_norm = self.clip_grad_norm(self.clip_grad) + timers('optimizer-clip-main-grad').stop() + + # count the zeros in the grads + num_zeros_in_grad = self.count_zeros() if \ + self.log_num_zeros_in_grad else None + + # Step the optimizer. + self.optimizer.step() + + # Update params from main params. + timers('optimizer-copy-main-to-model-params').start() + self._copy_main_params_to_model_params() + timers('optimizer-copy-main-to-model-params').stop() + + # Successful update. + return True, grad_norm, num_zeros_in_grad + + + def state_dict(self): + state_dict = {} + state_dict['optimizer'] = self.optimizer.state_dict() + if self.grad_scaler: + state_dict['grad_scaler'] = self.grad_scaler.state_dict() + state_dict['fp32_from_fp16_params'] = self.fp32_from_float16_groups + return state_dict + + + def load_state_dict(self, state_dict): + # Optimizer. + optimizer_key = 'optimizer' + if optimizer_key not in state_dict: + optimizer_key = 'optimizer_state_dict' + print_rank_0('***WARNING*** loading optimizer from ' + 'an old checkpoint ...') + self.optimizer.load_state_dict(state_dict[optimizer_key]) + + # Grad scaler. + if 'grad_scaler' not in state_dict: + print_rank_0('***WARNING*** found an old checkpoint, will not ' + 'load grad scaler ...') + else: + if self.grad_scaler: + self.grad_scaler.load_state_dict(state_dict['grad_scaler']) + else: + print_rank_0('***WARNING*** fould the grad scaler in the ' + 'checkpoint but it is None in the class. ' + 'Skipping loading grad scaler ...') + + # Copy data for the main params. + fp32_from_float16_params_key = 'fp32_from_fp16_params' + if fp32_from_float16_params_key not in state_dict: + fp32_from_float16_params_key = 'fp32_from_fp16' + for current_group, saved_group in zip( + self.fp32_from_float16_groups, + state_dict[fp32_from_float16_params_key]): + for current_param, saved_param in zip(current_group, saved_group): + current_param.data.copy_(saved_param.data) + + + +class FP32Optimizer(MegatronOptimizer): + + def __init__(self, optimizer, clip_grad, + log_num_zeros_in_grad, + params_have_main_grad): + + super(FP32Optimizer, self).__init__( + optimizer, clip_grad, log_num_zeros_in_grad, + params_have_main_grad) + + self._scale = torch.FloatTensor([1.0]).to(get_current_device()) + + + def zero_grad(self, set_to_none=True): + """Copied from torch.optim.optimizer""" + for group in self.optimizer.param_groups: + _zero_grad_group_helper(group['params'], set_to_none) + + + def get_loss_scale(self): + """FP32 optimizer does not do any scaling.""" + return self._scale + + + @torch.no_grad() + def step(self): + """Clip gradients (if needed) and step the base optimizer. + Always return successful since there is no overflow.""" + + # Copy main_grads to grads. + if self.params_have_main_grad: + for param_group in self.optimizer.param_groups: + for param in param_group['params']: + param.grad = param.main_grad + + # Clip gradients. + grad_norm = None + if self.clip_grad > 0.0: + grad_norm = self.clip_grad_norm(self.clip_grad) + + # count the zeros in the grads + num_zeros_in_grad = self.count_zeros() if \ + self.log_num_zeros_in_grad else None + + # Update parameters. + self.optimizer.step() + + # No overflow for FP32 optimizer. + return True, grad_norm, num_zeros_in_grad + + + def reload_model_params(self): + pass + + + def state_dict(self): + return self.optimizer.state_dict() + + + def load_state_dict(self, state_dict): + self.optimizer.load_state_dict(state_dict) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/__init__.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..311f2fdca99ee28b1bd2864649b626a8dad1c7e2 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/__init__.py @@ -0,0 +1,17 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from .tokenizer import build_tokenizer diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/bert_tokenization.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/bert_tokenization.py new file mode 100644 index 0000000000000000000000000000000000000000..a3aa6d907e31f38c9af9601f48a46c889ce1b675 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/bert_tokenization.py @@ -0,0 +1,402 @@ +# coding=utf-8 +# Copyright 2018 The Google AI Language Team 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 +# +# 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. + +"""Tokenization classes.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import re +import unicodedata +import six + + +def validate_case_matches_checkpoint(do_lower_case, init_checkpoint): + """Checks whether the casing config is consistent with the checkpoint name.""" + + # The casing has to be passed in by the user and there is no explicit check + # as to whether it matches the checkpoint. The casing information probably + # should have been stored in the bert_config.json file, but it's not, so + # we have to heuristically detect it to validate. + + if not init_checkpoint: + return + + m = re.match("^.*?([A-Za-z0-9_-]+)/bert_model.ckpt", init_checkpoint) + if m is None: + return + + model_name = m.group(1) + + lower_models = [ + "uncased_L-24_H-1024_A-16", "uncased_L-12_H-768_A-12", + "multilingual_L-12_H-768_A-12", "chinese_L-12_H-768_A-12" + ] + + cased_models = [ + "cased_L-12_H-768_A-12", "cased_L-24_H-1024_A-16", + "multi_cased_L-12_H-768_A-12" + ] + + is_bad_config = False + if model_name in lower_models and not do_lower_case: + is_bad_config = True + actual_flag = "False" + case_name = "lowercased" + opposite_flag = "True" + + if model_name in cased_models and do_lower_case: + is_bad_config = True + actual_flag = "True" + case_name = "cased" + opposite_flag = "False" + + if is_bad_config: + raise ValueError( + "You passed in `--do_lower_case=%s` with `--init_checkpoint=%s`. " + "However, `%s` seems to be a %s model, so you " + "should pass in `--do_lower_case=%s` so that the fine-tuning matches " + "how the model was pre-training. If this error is wrong, please " + "just comment out this check." % (actual_flag, init_checkpoint, + model_name, case_name, opposite_flag)) + + +def convert_to_unicode(text): + """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" + if six.PY3: + if isinstance(text, str): + return text + elif isinstance(text, bytes): + return text.decode("utf-8", "ignore") + else: + raise ValueError("Unsupported string type: %s" % (type(text))) + elif six.PY2: + if isinstance(text, str): + return text.decode("utf-8", "ignore") + elif isinstance(text, unicode): + return text + else: + raise ValueError("Unsupported string type: %s" % (type(text))) + else: + raise ValueError("Not running on Python2 or Python 3?") + + +def printable_text(text): + """Returns text encoded in a way suitable for print or `tf.logging`.""" + + # These functions want `str` for both Python2 and Python3, but in one case + # it's a Unicode string and in the other it's a byte string. + if six.PY3: + if isinstance(text, str): + return text + elif isinstance(text, bytes): + return text.decode("utf-8", "ignore") + else: + raise ValueError("Unsupported string type: %s" % (type(text))) + elif six.PY2: + if isinstance(text, str): + return text + elif isinstance(text, unicode): + return text.encode("utf-8") + else: + raise ValueError("Unsupported string type: %s" % (type(text))) + else: + raise ValueError("Not running on Python2 or Python 3?") + + +def load_vocab(vocab_file): + """Loads a vocabulary file into a dictionary.""" + vocab = collections.OrderedDict() + index = 0 + with open(vocab_file, "r") as reader: + while True: + token = convert_to_unicode(reader.readline()) + if not token: + break + token = token.strip() + vocab[token] = index + index += 1 + return vocab + + +def convert_by_vocab(vocab, items): + """Converts a sequence of [tokens|ids] using the vocab.""" + output = [] + for item in items: + output.append(vocab[item]) + return output + + +def convert_tokens_to_ids(vocab, tokens): + return convert_by_vocab(vocab, tokens) + + +def convert_ids_to_tokens(inv_vocab, ids): + return convert_by_vocab(inv_vocab, ids) + + +def whitespace_tokenize(text): + """Runs basic whitespace cleaning and splitting on a piece of text.""" + text = text.strip() + if not text: + return [] + tokens = text.split() + return tokens + + +class FullTokenizer(object): + """Runs end-to-end tokenziation.""" + + def __init__(self, vocab_file, do_lower_case=True): + self.vocab = load_vocab(vocab_file) + self.inv_vocab = {v: k for k, v in self.vocab.items()} + self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) + self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab) + + def tokenize(self, text): + split_tokens = [] + for token in self.basic_tokenizer.tokenize(text): + for sub_token in self.wordpiece_tokenizer.tokenize(token): + split_tokens.append(sub_token) + + return split_tokens + + def convert_tokens_to_ids(self, tokens): + return convert_by_vocab(self.vocab, tokens) + + def convert_ids_to_tokens(self, ids): + return convert_by_vocab(self.inv_vocab, ids) + + def vocab_size(self): + return len(self.vocab) + + +class BasicTokenizer(object): + """Runs basic tokenization (punctuation splitting, lower casing, etc.).""" + + def __init__(self, do_lower_case=True): + """Constructs a BasicTokenizer. + + Args: + do_lower_case: Whether to lower case the input. + """ + self.do_lower_case = do_lower_case + + def tokenize(self, text): + """Tokenizes a piece of text.""" + text = convert_to_unicode(text) + text = self._clean_text(text) + + # This was added on November 1st, 2018 for the multilingual and Chinese + # models. This is also applied to the English models now, but it doesn't + # matter since the English models were not trained on any Chinese data + # and generally don't have any Chinese data in them (there are Chinese + # characters in the vocabulary because Wikipedia does have some Chinese + # words in the English Wikipedia.). + text = self._tokenize_chinese_chars(text) + + orig_tokens = whitespace_tokenize(text) + split_tokens = [] + for token in orig_tokens: + if self.do_lower_case: + token = token.lower() + token = self._run_strip_accents(token) + split_tokens.extend(self._run_split_on_punc(token)) + + output_tokens = whitespace_tokenize(" ".join(split_tokens)) + return output_tokens + + def _run_strip_accents(self, text): + """Strips accents from a piece of text.""" + text = unicodedata.normalize("NFD", text) + output = [] + for char in text: + cat = unicodedata.category(char) + if cat == "Mn": + continue + output.append(char) + return "".join(output) + + def _run_split_on_punc(self, text): + """Splits punctuation on a piece of text.""" + chars = list(text) + i = 0 + start_new_word = True + output = [] + while i < len(chars): + char = chars[i] + if _is_punctuation(char): + output.append([char]) + start_new_word = True + else: + if start_new_word: + output.append([]) + start_new_word = False + output[-1].append(char) + i += 1 + + return ["".join(x) for x in output] + + def _tokenize_chinese_chars(self, text): + """Adds whitespace around any CJK character.""" + output = [] + for char in text: + cp = ord(char) + if self._is_chinese_char(cp): + output.append(" ") + output.append(char) + output.append(" ") + else: + output.append(char) + return "".join(output) + + def _is_chinese_char(self, cp): + """Checks whether CP is the codepoint of a CJK character.""" + # This defines a "chinese character" as anything in the CJK Unicode block: + # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) + # + # Note that the CJK Unicode block is NOT all Japanese and Korean characters, + # despite its name. The modern Korean Hangul alphabet is a different block, + # as is Japanese Hiragana and Katakana. Those alphabets are used to write + # space-separated words, so they are not treated specially and handled + # like the all of the other languages. + if ((cp >= 0x4E00 and cp <= 0x9FFF) or # + (cp >= 0x3400 and cp <= 0x4DBF) or # + (cp >= 0x20000 and cp <= 0x2A6DF) or # + (cp >= 0x2A700 and cp <= 0x2B73F) or # + (cp >= 0x2B740 and cp <= 0x2B81F) or # + (cp >= 0x2B820 and cp <= 0x2CEAF) or + (cp >= 0xF900 and cp <= 0xFAFF) or # + (cp >= 0x2F800 and cp <= 0x2FA1F)): # + return True + + return False + + def _clean_text(self, text): + """Performs invalid character removal and whitespace cleanup on text.""" + output = [] + for char in text: + cp = ord(char) + if cp == 0 or cp == 0xfffd or _is_control(char): + continue + if _is_whitespace(char): + output.append(" ") + else: + output.append(char) + return "".join(output) + + +class WordpieceTokenizer(object): + """Runs WordPiece tokenziation.""" + + def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200): + self.vocab = vocab + self.unk_token = unk_token + self.max_input_chars_per_word = max_input_chars_per_word + + def tokenize(self, text): + """Tokenizes a piece of text into its word pieces. + + This uses a greedy longest-match-first algorithm to perform tokenization + using the given vocabulary. + + For example: + input = "unaffable" + output = ["un", "##aff", "##able"] + + Args: + text: A single token or whitespace separated tokens. This should have + already been passed through `BasicTokenizer. + + Returns: + A list of wordpiece tokens. + """ + + text = convert_to_unicode(text) + + output_tokens = [] + for token in whitespace_tokenize(text): + chars = list(token) + if len(chars) > self.max_input_chars_per_word: + output_tokens.append(self.unk_token) + continue + + is_bad = False + start = 0 + sub_tokens = [] + while start < len(chars): + end = len(chars) + cur_substr = None + while start < end: + substr = "".join(chars[start:end]) + if start > 0: + substr = "##" + substr + if substr in self.vocab: + cur_substr = substr + break + end -= 1 + if cur_substr is None: + is_bad = True + break + sub_tokens.append(cur_substr) + start = end + + if is_bad: + output_tokens.append(self.unk_token) + else: + output_tokens.extend(sub_tokens) + return output_tokens + + +def _is_whitespace(char): + """Checks whether `chars` is a whitespace character.""" + # \t, \n, and \r are technically contorl characters but we treat them + # as whitespace since they are generally considered as such. + if char == " " or char == "\t" or char == "\n" or char == "\r": + return True + cat = unicodedata.category(char) + if cat == "Zs": + return True + return False + + +def _is_control(char): + """Checks whether `chars` is a control character.""" + # These are technically control characters but we count them as whitespace + # characters. + if char == "\t" or char == "\n" or char == "\r": + return False + cat = unicodedata.category(char) + if cat in ("Cc", "Cf"): + return True + return False + + +def _is_punctuation(char): + """Checks whether `chars` is a punctuation character.""" + cp = ord(char) + # We treat all non-letter/number ASCII as punctuation. + # Characters such as "^", "$", and "`" are not in the Unicode + # Punctuation class but we treat them as punctuation anyways, for + # consistency. + if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or + (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)): + return True + cat = unicodedata.category(char) + if cat.startswith("P"): + return True + return False diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/gpt2_tokenization.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/gpt2_tokenization.py new file mode 100644 index 0000000000000000000000000000000000000000..3f37e449089b8f779c93ac7f034085fd7607bfb0 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/gpt2_tokenization.py @@ -0,0 +1,321 @@ +# coding=utf-8 +# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team. +# +# 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. + +"""Tokenization classes for OpenAI GPT.""" + +from __future__ import (absolute_import, division, print_function, + unicode_literals) + +import sys +import json +import logging +import os +import regex as re +from io import open + +try: + from functools import lru_cache +except ImportError: + # Just a dummy decorator to get the checks to run on python2 + # because honestly I don't want to support a byte-level unicode BPE + # tokenizer on python 2 right now. + def lru_cache(): + return lambda func: func + + +logger = logging.getLogger(__name__) + +PRETRAINED_VOCAB_ARCHIVE_MAP = { + 'gpt2': "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json", +} +PRETRAINED_MERGES_ARCHIVE_MAP = { + 'gpt2': "https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt", +} +PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP = { + 'gpt2': 1024, +} +VOCAB_NAME = 'vocab.json' +MERGES_NAME = 'merges.txt' +SPECIAL_TOKENS_NAME = 'special_tokens.txt' + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + _chr = unichr if sys.version_info[0] == 2 else chr + bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + \ + list(range(ord("®"), ord("ÿ") + 1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8 + n) + n += 1 + cs = [_chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +class GPT2Tokenizer(object): + """ + GPT-2 BPE tokenizer. Peculiarities: + - Byte-level BPE + """ + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): + """ + Instantiate a PreTrainedBertModel from a pre-trained model file. + Download and cache the pre-trained model file if needed. + """ + if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHIVE_MAP: + vocab_file = PRETRAINED_VOCAB_ARCHIVE_MAP[pretrained_model_name_or_path] + merges_file = PRETRAINED_MERGES_ARCHIVE_MAP[pretrained_model_name_or_path] + special_tokens_file = None + else: + vocab_file = os.path.join(pretrained_model_name_or_path, VOCAB_NAME) + merges_file = os.path.join(pretrained_model_name_or_path, MERGES_NAME) + special_tokens_file = os.path.join(pretrained_model_name_or_path, SPECIAL_TOKENS_NAME) + if not os.path.exists(special_tokens_file): + special_tokens_file = None + else: + logger.info("loading special tokens file {}".format(special_tokens_file)) + # redirect to the cache, if necessary + try: + from .file_utils import cached_path + resolved_vocab_file = cached_path(vocab_file, cache_dir=cache_dir) + resolved_merges_file = cached_path(merges_file, cache_dir=cache_dir) + except EnvironmentError: + logger.error( + "Model name '{}' was not found in model name list ({}). " + "We assumed '{}' was a path or url but couldn't find files {} and {} " + "at this path or url.".format( + pretrained_model_name_or_path, + ', '.join(PRETRAINED_VOCAB_ARCHIVE_MAP.keys()), + pretrained_model_name_or_path, + vocab_file, merges_file)) + return None + if resolved_vocab_file == vocab_file and resolved_merges_file == merges_file: + logger.info("loading vocabulary file {}".format(vocab_file)) + logger.info("loading merges file {}".format(merges_file)) + else: + logger.info("loading vocabulary file {} from cache at {}".format( + vocab_file, resolved_vocab_file)) + logger.info("loading merges file {} from cache at {}".format( + merges_file, resolved_merges_file)) + if pretrained_model_name_or_path in PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP: + # if we're using a pretrained model, ensure the tokenizer wont index sequences longer + # than the number of positional embeddings + max_len = PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP[pretrained_model_name_or_path] + kwargs['max_len'] = min(kwargs.get('max_len', int(1e12)), max_len) + # Instantiate tokenizer. + if special_tokens_file and 'special_tokens' not in kwargs: + special_tokens = open(special_tokens_file, encoding='utf-8').read().split('\n')[:-1] + else: + special_tokens = kwargs.pop('special_tokens', []) + tokenizer = cls( + resolved_vocab_file, + resolved_merges_file, + special_tokens=special_tokens, + *inputs, + **kwargs) + return tokenizer + + def __init__(self, vocab_file, merges_file, errors='replace', + special_tokens=None, max_len=None): + self.max_len = max_len if max_len is not None else int(1e12) + self.encoder = json.load(open(vocab_file)) + self.decoder = {v: k for k, v in self.encoder.items()} + self.errors = errors # how to handle errors in decoding + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + bpe_data = open(merges_file, encoding='utf-8').read().split('\n')[1:-1] + bpe_merges = [tuple(merge.split()) for merge in bpe_data] + self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges)))) + self.cache = {} + + # Should haved added re.IGNORECASE so BPE merges can happen for + # capitalized versions of contractions + self.pat = re.compile( + r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""") + + self.special_tokens = {} + self.special_tokens_decoder = {} + self.set_special_tokens(special_tokens) + + def __len__(self): + return len(self.encoder) + len(self.special_tokens) + + def set_special_tokens(self, special_tokens): + """ Add a list of additional tokens to the encoder. + The additional tokens are indexed starting from the last index of the + current vocabulary in the order of the `special_tokens` list. + """ + if not special_tokens: + self.special_tokens = {} + self.special_tokens_decoder = {} + return + self.special_tokens = dict((tok, len(self.encoder) + i) + for i, tok in enumerate(special_tokens)) + self.special_tokens_decoder = {v: k for k, v in self.special_tokens.items()} + logger.info("Special tokens {}".format(self.special_tokens)) + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token) + pairs = get_pairs(word) + + if not pairs: + return token + + while True: + bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except BaseException: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word) - 1 and word[i + 1] == second: + new_word.append(first + second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def tokenize(self, text): + """ Tokenize a string. """ + bpe_tokens = [] + for token in re.findall(self.pat, text): + if sys.version_info[0] == 2: + token = ''.join(self.byte_encoder[ord(b)] for b in token) + else: + token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) + bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def convert_tokens_to_ids(self, tokens): + """ Converts a sequence of tokens into ids using the vocab. """ + ids = [] + if isinstance(tokens, str) or (sys.version_info[0] == 2 and isinstance(tokens, unicode)): + if tokens in self.special_tokens: + return self.special_tokens[tokens] + else: + return self.encoder.get(tokens, 0) + for token in tokens: + if token in self.special_tokens: + ids.append(self.special_tokens[token]) + else: + ids.append(self.encoder.get(token, 0)) + if len(ids) > self.max_len: + logger.warning( + "Token indices sequence length is longer than the specified maximum " + " sequence length for this OpenAI GPT model ({} > {}). Running this" + " sequence through the model will result in indexing errors".format( + len(ids), self.max_len) + ) + return ids + + def convert_ids_to_tokens(self, ids, skip_special_tokens=False): + """Converts a sequence of ids in BPE tokens using the vocab.""" + tokens = [] + for i in ids: + if i in self.special_tokens_decoder: + if not skip_special_tokens: + tokens.append(self.special_tokens_decoder[i]) + else: + tokens.append(self.decoder[i]) + return tokens + + def encode(self, text): + return self.convert_tokens_to_ids(self.tokenize(text)) + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors=self.errors) + return text + + def save_vocabulary(self, vocab_path): + """Save the tokenizer vocabulary and merge files to a directory.""" + if not os.path.isdir(vocab_path): + logger.error("Vocabulary path ({}) should be a directory".format(vocab_path)) + return + vocab_file = os.path.join(vocab_path, VOCAB_NAME) + merge_file = os.path.join(vocab_path, MERGES_NAME) + special_tokens_file = os.path.join(vocab_path, SPECIAL_TOKENS_NAME) + + with open(vocab_file, 'w', encoding='utf-8') as f: + f.write(json.dumps(self.encoder, ensure_ascii=False)) + + index = 0 + with open(merge_file, "w", encoding="utf-8") as writer: + writer.write(u'#version: 0.2\n') + for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]): + if index != token_index: + logger.warning("Saving vocabulary to {}: BPE merge indices are not consecutive." + " Please check that the tokenizer is not corrupted!".format(merge_file)) + index = token_index + writer.write(' '.join(bpe_tokens) + u'\n') + index += 1 + + index = len(self.encoder) + with open(special_tokens_file, 'w', encoding='utf-8') as writer: + for token, token_index in sorted(self.special_tokens.items(), key=lambda kv: kv[1]): + if index != token_index: + logger.warning("Saving special tokens vocabulary to {}: BPE indices are not consecutive." + " Please check that the tokenizer is not corrupted!".format(special_tokens_file)) + index = token_index + writer.write(token + u'\n') + index += 1 + + return vocab_file, merge_file, special_tokens_file diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/sentencepiece_tokenization.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/sentencepiece_tokenization.py new file mode 100644 index 0000000000000000000000000000000000000000..bd9a3ea275c646738cdf5727493904238e541964 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/sentencepiece_tokenization.py @@ -0,0 +1,78 @@ +"""SentencePiece tokenizer.""" + +from __future__ import (absolute_import, division, print_function, unicode_literals) + +import os +import logging +import sentencepiece +import numpy as np + +logger = logging.getLogger(__name__) + + +class SentencePieceTokenizer(object): + def __init__(self, model_path): + if not model_path or not os.path.exists(model_path): + raise ValueError(f"model_path: {model_path} is invalid") + + logger.info(f"Loading SentencePiece model from {model_path}") + self.tokenizer = sentencepiece.SentencePieceProcessor() + self.tokenizer.Load(model_path) + self.original_vocab_size = self.tokenizer.get_piece_size() + self.vocab_size = self.tokenizer.get_piece_size() + self.vocab = {_id: self.tokenizer.id_to_piece(_id) for _id in range(self.vocab_size)} + self.inv_vocab = {v: k for k, v in self.vocab.items()} + + def encode(self, text): + """ Text to token ids """ + return self.text_to_ids(text) + + def decode(self, ids): + """ Token ids to text """ + return self.ids_to_text(ids) + + def text_to_ids(self, text): + return self.tokenizer.encode_as_ids(text) + + def ids_to_text(self, ids): + if isinstance(ids, np.ndarray): + ids = ids.tolist() + return self.tokenizer.decode_ids(ids) + + def token_to_id(self, token): + return self.tokenizer.piece_to_id(token) + + def ids_to_tokens(self, ids): + if isinstance(ids, np.ndarray): + ids = ids.tolist() + return [self.tokenizer.id_to_piece(_id) for _id in ids] + + def tokens_to_ids(self, tokens): + if isinstance(tokens, str): + tokens = [tokens] + ids = [] + for token in tokens: + ids.append(self.token_to_id(token)) + return ids + + def tokens_to_text(self, tokens): + return self.tokenizer.decode_pieces(tokens) + + def text_to_tokens(self, text): + return self.tokenizer.encode_as_pieces(text) + + @property + def pad_id(self): + return self.tokenizer.pad_id() + + @property + def bos_id(self): + return self.tokenizer.bos_id() + + @property + def eos_id(self): + return self.tokenizer.eos_id() + + @property + def unk_id(self): + return self.tokenizer.unk_id() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/tokenizer.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a49306b57337cc3beb2a8e88cfbee17109962a --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/megatron/tokenizer/tokenizer.py @@ -0,0 +1,330 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Megatron tokenizers.""" + +from abc import ABC +from abc import abstractmethod + +from .bert_tokenization import FullTokenizer as FullBertTokenizer +from .gpt2_tokenization import GPT2Tokenizer +from .sentencepiece_tokenization import SentencePieceTokenizer + + +def build_tokenizer(args): + """Initialize tokenizer.""" + if args.rank == 0: + print('> building {} tokenizer ...'.format(args.tokenizer_type), + flush=True) + + # Select and instantiate the tokenizer. + if args.tokenizer_type == 'BertWordPieceLowerCase': + assert args.vocab_file is not None + tokenizer = _BertWordPieceTokenizer(vocab_file=args.vocab_file, + lower_case=True, + vocab_extra_ids=args.vocab_extra_ids) + elif args.tokenizer_type == 'BertWordPieceCase': + assert args.vocab_file is not None + tokenizer = _BertWordPieceTokenizer(vocab_file=args.vocab_file, + lower_case=False, + vocab_extra_ids=args.vocab_extra_ids) + elif args.tokenizer_type == 'GPT2BPETokenizer': + assert args.vocab_file is not None + assert args.merge_file is not None + tokenizer = _GPT2BPETokenizer(args.vocab_file, args.merge_file) + elif args.tokenizer_type == 'SentencePieceTokenizer': + assert args.tokenizer_model_file is not None + tokenizer = _SentencePieceTokenizer(args.tokenizer_model_file, args.tokenizer_eod_id) + else: + raise NotImplementedError('{} tokenizer is not ' + 'implemented.'.format(args.tokenizer_type)) + + # Add vocab size. + args.padded_vocab_size = _vocab_size_with_padding(tokenizer.vocab_size, + args) + + return tokenizer + + +def _vocab_size_with_padding(orig_vocab_size, args): + """Pad vocab size so it is divisible by model parallel size and + still having GPU friendly size.""" + + after = orig_vocab_size + multiple = args.make_vocab_size_divisible_by * \ + args.tensor_model_parallel_size + while (after % multiple) != 0: + after += 1 + if args.rank == 0: + print(' > padded vocab (size: {}) with {} dummy tokens ' + '(new size: {})'.format( + orig_vocab_size, after - orig_vocab_size, after), flush=True) + return after + + +class AbstractTokenizer(ABC): + """Abstract class for tokenizer.""" + + def __init__(self, name): + self.name = name + super().__init__() + + @property + @abstractmethod + def vocab_size(self): + pass + + @property + @abstractmethod + def vocab(self): + """Dictionary from vocab text token to id token.""" + pass + + @property + @abstractmethod + def inv_vocab(self): + """Dictionary from vocab id token to text token.""" + pass + + @abstractmethod + def tokenize(self, text): + pass + + def detokenize(self, token_ids): + raise NotImplementedError('detokenizer is not implemented for {} ' + 'tokenizer'.format(self.name)) + + @property + def cls(self): + raise NotImplementedError('CLS is not provided for {} ' + 'tokenizer'.format(self.name)) + + @property + def sep(self): + raise NotImplementedError('SEP is not provided for {} ' + 'tokenizer'.format(self.name)) + + @property + def pad(self): + raise NotImplementedError('PAD is not provided for {} ' + 'tokenizer'.format(self.name)) + + @property + def eod(self): + raise NotImplementedError('EOD is not provided for {} ' + 'tokenizer'.format(self.name)) + + @property + def mask(self): + raise NotImplementedError('MASK is not provided for {} ' + 'tokenizer'.format(self.name)) + + +class _BertWordPieceTokenizer(AbstractTokenizer): + """Original BERT wordpiece tokenizer.""" + + def __init__(self, vocab_file, lower_case=True, vocab_extra_ids=0): + if lower_case: + name = 'BERT Lower Case' + else: + name = 'BERT Upper Case' + super().__init__(name) + self.tokenizer = FullBertTokenizer(vocab_file, do_lower_case=lower_case) + self.cls_id = self.tokenizer.vocab['[CLS]'] + self.sep_id = self.tokenizer.vocab['[SEP]'] + self.pad_id = self.tokenizer.vocab['[PAD]'] + self.mask_id = self.tokenizer.vocab['[MASK]'] + self._additional_special_tokens = [] + + # (dsachan) Add BOS and EOS tokens + SPECIAL_TOKENS = {'eos_token': '[EOS]', + 'bos_token': '[BOS]'} + self._bos_token = '[BOS]' + self.add_token(self._bos_token) + self._bos_token_id = self.vocab.get(self._bos_token) + + self._eos_token = '[EOS]' + self.add_token(self._eos_token) + self._eos_token_id = self.vocab.get(self._eos_token) + + # (dsachan) Add additional special tokens + # These can be used as sentinel tokens in T5 model inputs + additional_special_tokens = [] + additional_special_tokens.extend( + ["".format(i) for i in range(vocab_extra_ids)]) + self.add_additional_special_tokens(additional_special_tokens) + + def add_token(self, token): + if token not in self.vocab: + self.inv_vocab[self.vocab_size] = token + # self.vocab_size comes from len(vocab) + # and it will increase as we add elements + self.vocab[token] = self.vocab_size + + def add_additional_special_tokens(self, tokens_list): + setattr(self, "additional_special_tokens", tokens_list) + for value in tokens_list: + self.add_token(value) + + @property + def vocab_size(self): + return self.tokenizer.vocab_size() + + @property + def vocab(self): + return self.tokenizer.vocab + + @property + def inv_vocab(self): + return self.tokenizer.inv_vocab + + def tokenize(self, text): + text_tokens = self.tokenizer.tokenize(text) + return self.tokenizer.convert_tokens_to_ids(text_tokens) + + def decode(self, ids): + tokens = self.tokenizer.convert_ids_to_tokens(ids) + return self.tokenizer.convert_tokens_to_string(tokens) + + def decode_token_ids(self, token_ids): + tokens = self.tokenizer.convert_ids_to_tokens(token_ids) + exclude_list = ['[PAD]', '[CLS]'] + non_pads = [t for t in tokens if t not in exclude_list] + + result = "" + for s in non_pads: + if s.startswith("##"): + result += s[2:] + else: + result += " " + s + + return result + + @property + def cls(self): + return self.cls_id + + @property + def sep(self): + return self.sep_id + + @property + def pad(self): + return self.pad_id + + @property + def mask(self): + return self.mask_id + + @property + def bos_token(self): + """ Beginning of sentence token id """ + return self._bos_token + + @property + def eos_token(self): + """ End of sentence token id """ + return self._eos_token + + @property + def additional_special_tokens(self): + """ All the additional special tokens you may want to use (list of strings).""" + return self._additional_special_tokens + + @property + def bos_token_id(self): + """ Id of the beginning of sentence token in the vocabulary.""" + return self._bos_token_id + + @property + def eos_token_id(self): + """ Id of the end of sentence token in the vocabulary.""" + return self._eos_token_id + + @property + def additional_special_tokens_ids(self): + """ Ids of all the additional special tokens in the vocabulary (list of integers).""" + return [self.vocab.get(token) for token in self._additional_special_tokens] + + @additional_special_tokens.setter + def additional_special_tokens(self, value): + self._additional_special_tokens = value + + +class _GPT2BPETokenizer(AbstractTokenizer): + """Original GPT2 BPE tokenizer.""" + + def __init__(self, vocab_file, merge_file): + name = 'GPT2 BPE' + super().__init__(name) + + self.tokenizer = GPT2Tokenizer(vocab_file, merge_file, errors='replace', + special_tokens=[], max_len=None) + self.eod_id = self.tokenizer.encoder['<|endoftext|>'] + + @property + def vocab_size(self): + return len(self.tokenizer.encoder) + + @property + def vocab(self): + return self.tokenizer.encoder + + @property + def inv_vocab(self): + return self.tokenizer.decoder + + def tokenize(self, text): + return self.tokenizer.encode(text) + + def detokenize(self, token_ids): + return self.tokenizer.decode(token_ids) + + @property + def eod(self): + return self.eod_id + + +class _SentencePieceTokenizer(AbstractTokenizer): + """Wrapper for SentencePiece tokenizer package https://github.com/google/sentencepiece""" + + def __init__(self, model_file, eod_id): + name = 'SentencePiece' + super().__init__(name) + + self.tokenizer = SentencePieceTokenizer(model_file) + self.eod_id = eod_id + + @property + def vocab_size(self): + return self.tokenizer.vocab_size + + @property + def vocab(self): + return self.tokenizer.vocab + + @property + def inv_vocab(self): + return self.tokenizer.inv_vocab + + def tokenize(self, text): + return self.tokenizer.encode(text) + + def detokenize(self, token_ids): + return self.tokenizer.decode(token_ids) + + @property + def eod(self): + return self.eod_id diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/LICENSE b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e609df0d8cd3b5d11a1ea962a56b604b70846a5 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/LICENSE @@ -0,0 +1,82 @@ +Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors + +CreativeML Open RAIL-M +dated August 22, 2022 + +Section I: PREAMBLE + +Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation. + +Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations. + +In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation. + +Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI. + +This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model. + +NOW THEREFORE, You and Licensor agree as follows: + +1. Definitions + +- "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document. +- "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License. +- "Output" means the results of operating a Model as embodied in informational content resulting therefrom. +- "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material. +- "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model. +- "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any. +- "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access. +- "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model. +- "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator. +- "Third Parties" means individuals or legal entities that are not under common control with Licensor or You. +- "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model 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 Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." +- "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model. + +Section II: INTELLECTUAL PROPERTY RIGHTS + +Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III. + +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, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model. +3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, 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 Model 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 Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed. + +Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION + +4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions: +Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material. +You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License; +You must cause any modified files to carry prominent notices stating that You changed the files; +You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model. +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License. +5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5). +6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License. + +Section IV: OTHER PROVISIONS + +7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model. +8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors. +9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (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 Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License. +10. 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 Model and the Complementary Material (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. +11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material 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. +12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein. + +END OF TERMS AND CONDITIONS + + + + +Attachment A + +Use Restrictions + +You agree not to use the Model or Derivatives of the Model: +- In any way that violates any applicable national, federal, state, local or international law or regulation; +- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way; +- To generate or disseminate verifiably false information and/or content with the purpose of harming others; +- To generate or disseminate personal identifiable information that can be used to harm an individual; +- To defame, disparage or otherwise harass others; +- For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation; +- For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics; +- To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm; +- For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories; +- To provide medical advice and medical results interpretation; +- To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use). diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/dir.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/dir.sh new file mode 100644 index 0000000000000000000000000000000000000000..a75945c660013c7d13243e8c66fe2613885778d4 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/dir.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +path="/software/users/msinha/share/sd/Final_Submission/results" + +str="-" + +declare -A dir_cr_times + +for dir in "$path"/*/; +do + if [ -d "$dir" ] && [[ "$dir" == *"$str"* ]] ; then + cr_time=$(stat -c %Y "$dir") + dir_cr_times["$dir"]=$cr_time + fi +done + +sorted_dirs=($(for dir in "${!dir_cr_times[@]}"; do + echo "$dir_cr_times[$dir]" +done | sort -n -r -k2 | awk '{print $1}')) + +for dir in "${sorted_dirs[@]}"; do + d_p=${dir%"]"} + d_p=${d_p#"["} + echo ${d_p} +done diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/__init__.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/composable_data_module.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/composable_data_module.py new file mode 100644 index 0000000000000000000000000000000000000000..b3fb8b6388659291247abffd26be4d17235f009c --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/composable_data_module.py @@ -0,0 +1,30 @@ +from functools import partial + +import lightning.pytorch as pl + +from ldm.util import instantiate_from_config + + +class ComposableDataModule(pl.LightningDataModule): + + def __init__(self, train=None, validation=None, test=None, predict=None): + super().__init__() + self.dataset_configs = dict() + if train is not None: + self.dataset_configs["train"] = train + self.train_dataloader = partial(self._gen_dataloader, mode="train") + if validation is not None: + self.dataset_configs["validation"] = validation + self.val_dataloader = partial(self._gen_dataloader, mode="validation") + if test is not None: + self.dataset_configs["test"] = test + self.test_dataloader = partial(self._gen_dataloader, mode="test") + if predict is not None: + self.dataset_configs["predict"] = predict + self.predict_dataloader = partial(self._gen_dataloader, mode="predict") + + def setup(self, stage=None): + self.datasets = dict((k, instantiate_from_config(self.dataset_configs[k])) for k in self.dataset_configs) + + def _gen_dataloader(self, mode): + return self.datasets[mode] diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/tsv.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/tsv.py new file mode 100644 index 0000000000000000000000000000000000000000..c87233132c12d5c05774297c9782d02325e62e38 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/tsv.py @@ -0,0 +1,27 @@ +import pandas as pd +from torch.utils.data import Dataset, DataLoader + + +class TsvDataset(Dataset): + def __init__(self, annotations_file, keys): + self.df = pd.read_csv(annotations_file, sep='\t', header=0) + self.keys = keys + + def __len__(self): + return len(self.df) + + def __getitem__(self, idx): + sample = {} + for key in self.keys: + sample[key] = self.df[key].iloc[idx] + return sample + + +def build_dataloader(annotations_file, + keys, + batch_size, + shuffle=False, + num_workers=1, + pin_memory=True): + dataset = TsvDataset(annotations_file, keys=keys) + return DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, pin_memory=pin_memory) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/webdatasets.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/webdatasets.py new file mode 100644 index 0000000000000000000000000000000000000000..bd1d7d77d3114db64678379038b6353dfdb7424a --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/data/webdatasets.py @@ -0,0 +1,55 @@ +from torch.utils.data import default_collate +from torchvision import transforms + +import webdataset as wds + +from ldm.util import instantiate_from_config +from ldm.data.utils import instantiate_transforms_from_config, identity, keys_filter + +from PIL import Image + +Image.MAX_IMAGE_PIXELS = None + + +def build_dataloader( + urls, + batch_size, + shuffle=-1, + partial=False, + decode=None, + metadata_filters=None, + keep_only_keys=None, + transformations=None, + num_workers=1, + cache_size=-1, + cache_dir=None, + persistent_workers=True): + # TODO(ahmadki): WebDataset supports a "PipeLine" format which is more convenient than the "fluid" format used here + # But fluid format results in an error (TypeError: 'FilterFunction' object is not iterable) + # which I haven't been able to debug yet. + dataset = wds.WebDataset(urls=urls, resampled=True, cache_size=cache_size, cache_dir=cache_dir) + + # Filter samples based on metadata + for filter in metadata_filters or []: + dataset = dataset.select(instantiate_from_config(filter)) + + # shuffle + dataset = dataset.shuffle(size=shuffle) + + # decode + if isinstance(decode, str): + dataset = dataset.decode(decode) + else: + dataset = dataset.decode() + + # Filter keys + if keep_only_keys: + dataset = dataset.map(keys_filter(keep_only_keys)) + + # Apply transformations + if transformations is not None: + transformations_dict = {k: transforms.Compose([instantiate_transforms_from_config(t) for t in transformations[k]]) for k in transformations.keys()} + dataset = dataset.map_dict(**transformations_dict) + + dataset = dataset.batched(batch_size, partial=partial, collation_fn=default_collate) + return wds.WebLoader(dataset, batch_size=None, shuffle=False, num_workers=num_workers, persistent_workers=persistent_workers) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/modules/fid/fid_score.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/modules/fid/fid_score.py new file mode 100644 index 0000000000000000000000000000000000000000..a388b9ef7b0e14f97c7058e22b63ae1655919eca --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/ldm/modules/fid/fid_score.py @@ -0,0 +1,325 @@ +"""Calculates the Frechet Inception Distance (FID) to evalulate GANs + +The FID metric calculates the distance between two distributions of images. +Typically, we have summary statistics (mean & covariance matrix) of one +of these distributions, while the 2nd distribution is given by a GAN. + +When run as a stand-alone program, it compares the distribution of +images that are stored as PNG/JPEG at a specified location with a +distribution given by summary statistics (in pickle format). + +The FID is calculated by assuming that X_1 and X_2 are the activations of +the pool_3 layer of the inception net for generated samples and real world +samples respectively. + +See --help to see further details. + +Code apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead +of Tensorflow + +Copyright 2018 Institute of Bioinformatics, JKU Linz + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import os +import pathlib +from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser + +import numpy as np +import torch +import torchvision.transforms as TF +from PIL import Image +from scipy import linalg +from torch.nn.functional import adaptive_avg_pool2d + +try: + from tqdm import tqdm +except ImportError: + # If tqdm is not available, provide a mock version of it + def tqdm(x): + return x + +try: + from ldm.modules.fid.inception import InceptionV3 +except ImportError: + from inception import InceptionV3 + +parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) +parser.add_argument('--batch-size', type=int, default=50, + help='Batch size to use') +parser.add_argument('--num-workers', type=int, + help=('Number of processes to use for data loading. ' + 'Defaults to `min(8, num_cpus)`')) +parser.add_argument('--device', type=str, default=None, + help='Device to use. Like cuda, cuda:0 or cpu') +parser.add_argument('--dims', type=int, default=2048, + choices=list(InceptionV3.BLOCK_INDEX_BY_DIM), + help=('Dimensionality of Inception features to use. ' + 'By default, uses pool3 features')) +parser.add_argument('--save-stats', action='store_true', + help=('Generate an npz archive from a directory of samples. ' + 'The first path is used as input and the second as output.')) +parser.add_argument('path', type=str, nargs=2, + help=('Paths to the generated images or ' + 'to .npz statistic files')) + +IMAGE_EXTENSIONS = {'bmp', 'jpg', 'jpeg', 'pgm', 'png', 'ppm', + 'tif', 'tiff', 'webp'} + + +class ImagePathDataset(torch.utils.data.Dataset): + def __init__(self, files, transforms=None): + self.files = files + self.transforms = transforms + + def __len__(self): + return len(self.files) + + def __getitem__(self, i): + path = self.files[i] + img = Image.open(path).convert('RGB') + if self.transforms is not None: + img = self.transforms(img) + return img + + +def get_activations(files, model, batch_size=50, dims=2048, device='cpu', + num_workers=1): + """Calculates the activations of the pool_3 layer for all images. + + Params: + -- files : List of image files paths + -- model : Instance of inception model + -- batch_size : Batch size of images for the model to process at once. + Make sure that the number of samples is a multiple of + the batch size, otherwise some samples are ignored. This + behavior is retained to match the original FID score + implementation. + -- dims : Dimensionality of features returned by Inception + -- device : Device to run calculations + -- num_workers : Number of parallel dataloader workers + + Returns: + -- A numpy array of dimension (num images, dims) that contains the + activations of the given tensor when feeding inception with the + query tensor. + """ + model.eval() + + if batch_size > len(files): + print(('Warning: batch size is bigger than the data size. ' + 'Setting batch size to data size')) + batch_size = len(files) + + dataset = ImagePathDataset(files, transforms=TF.ToTensor()) + dataloader = torch.utils.data.DataLoader(dataset, + batch_size=batch_size, + shuffle=False, + drop_last=False, + num_workers=num_workers) + + pred_arr = np.empty((len(files), dims)) + + start_idx = 0 + + for batch in tqdm(dataloader): + batch = batch.to(device) + + with torch.no_grad(): + pred = model(batch)[0] + + # If model output is not scalar, apply global spatial average pooling. + # This happens if you choose a dimensionality not equal 2048. + if pred.size(2) != 1 or pred.size(3) != 1: + pred = adaptive_avg_pool2d(pred, output_size=(1, 1)) + + pred = pred.squeeze(3).squeeze(2).cpu().numpy() + + pred_arr[start_idx:start_idx + pred.shape[0]] = pred + + start_idx = start_idx + pred.shape[0] + + return pred_arr + + +def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): + """Numpy implementation of the Frechet Distance. + The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) + and X_2 ~ N(mu_2, C_2) is + d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). + + Stable version by Dougal J. Sutherland. + + Params: + -- mu1 : Numpy array containing the activations of a layer of the + inception net (like returned by the function 'get_predictions') + for generated samples. + -- mu2 : The sample mean over activations, precalculated on an + representative data set. + -- sigma1: The covariance matrix over activations for generated samples. + -- sigma2: The covariance matrix over activations, precalculated on an + representative data set. + + Returns: + -- : The Frechet Distance. + """ + + mu1 = np.atleast_1d(mu1) + mu2 = np.atleast_1d(mu2) + + sigma1 = np.atleast_2d(sigma1) + sigma2 = np.atleast_2d(sigma2) + + assert mu1.shape == mu2.shape, \ + 'Training and test mean vectors have different lengths' + assert sigma1.shape == sigma2.shape, \ + 'Training and test covariances have different dimensions' + + diff = mu1 - mu2 + + # Product might be almost singular + covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False) + if not np.isfinite(covmean).all(): + msg = ('fid calculation produces singular product; ' + 'adding %s to diagonal of cov estimates') % eps + print(msg) + offset = np.eye(sigma1.shape[0]) * eps + covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset)) + + # Numerical error might give slight imaginary component + if np.iscomplexobj(covmean): + if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3): + m = np.max(np.abs(covmean.imag)) + raise ValueError('Imaginary component {}'.format(m)) + covmean = covmean.real + + tr_covmean = np.trace(covmean) + + return (diff.dot(diff) + np.trace(sigma1) + + np.trace(sigma2) - 2 * tr_covmean) + + +def calculate_activation_statistics(files, model, batch_size=50, dims=2048, + device='cpu', num_workers=1): + """Calculation of the statistics used by the FID. + Params: + -- files : List of image files paths + -- model : Instance of inception model + -- batch_size : The images numpy array is split into batches with + batch size batch_size. A reasonable batch size + depends on the hardware. + -- dims : Dimensionality of features returned by Inception + -- device : Device to run calculations + -- num_workers : Number of parallel dataloader workers + + Returns: + -- mu : The mean over samples of the activations of the pool_3 layer of + the inception model. + -- sigma : The covariance matrix of the activations of the pool_3 layer of + the inception model. + """ + act = get_activations(files, model, batch_size, dims, device, num_workers) + mu = np.mean(act, axis=0) + sigma = np.cov(act, rowvar=False) + return mu, sigma + + +def compute_statistics_of_path(path, model, batch_size, dims, device, + num_workers=1): + if path.endswith('.npz'): + with np.load(path) as f: + m, s = f['mu'][:], f['sigma'][:] + else: + path = pathlib.Path(path) + files = sorted([file for ext in IMAGE_EXTENSIONS + for file in path.glob('*.{}'.format(ext))]) + m, s = calculate_activation_statistics(files, model, batch_size, + dims, device, num_workers) + + return m, s + + +def calculate_fid_given_paths(paths, batch_size, device, dims, num_workers=1): + """Calculates the FID of two paths""" + for p in paths: + if not os.path.exists(p): + raise RuntimeError('Invalid path: %s' % p) + + block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims] + + model = InceptionV3([block_idx]).to(device) + + m1, s1 = compute_statistics_of_path(paths[0], model, batch_size, + dims, device, num_workers) + m2, s2 = compute_statistics_of_path(paths[1], model, batch_size, + dims, device, num_workers) + fid_value = calculate_frechet_distance(m1, s1, m2, s2) + + return fid_value + + +def save_fid_stats(paths, batch_size, device, dims, num_workers=1): + """Calculates the FID of two paths""" + if not os.path.exists(paths[0]): + raise RuntimeError('Invalid path: %s' % paths[0]) + + if os.path.exists(paths[1]): + raise RuntimeError('Existing output file: %s' % paths[1]) + + block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims] + + model = InceptionV3([block_idx]).to(device) + + print(f"Saving statistics for {paths[0]}") + + m1, s1 = compute_statistics_of_path(paths[0], model, batch_size, + dims, device, num_workers) + + np.savez_compressed(paths[1], mu=m1, sigma=s1) + + +def main(): + args = parser.parse_args() + + if args.device is None: + device = torch.device('cuda' if (torch.cuda.is_available()) else 'cpu') + else: + device = torch.device(args.device) + + if args.num_workers is None: + try: + num_cpus = len(os.sched_getaffinity(0)) + except AttributeError: + # os.sched_getaffinity is not available under Windows, use + # os.cpu_count instead (which may not return the *available* number + # of CPUs). + num_cpus = os.cpu_count() + + num_workers = min(num_cpus, 8) if num_cpus is not None else 0 + else: + num_workers = args.num_workers + + if args.save_stats: + save_fid_stats(args.path, args.batch_size, device, args.dims, num_workers) + return + + fid_value = calculate_fid_given_paths(args.path, + args.batch_size, + device, + args.dims, + num_workers) + print('FID: ', fid_value) + + +if __name__ == '__main__': + main() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/main.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/main.py new file mode 100644 index 0000000000000000000000000000000000000000..d5cca71ff97765540e8d0958adf776371f42d9cf --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/main.py @@ -0,0 +1,869 @@ +import argparse +import datetime +import glob +import json +import os +import sys +import time +import random + +import numpy as np +import torch +import torchvision +import copy + + +try: + import lightning.pytorch as pl +except: + import pytorch_lightning as pl + +from functools import partial + +from omegaconf import OmegaConf +from prefetch_generator import BackgroundGenerator +from torch.utils.data import DataLoader, Dataset + +try: + from lightning.pytorch import seed_everything + from lightning.pytorch.callbacks import Callback + from lightning.pytorch.trainer import Trainer + from lightning.pytorch.utilities import rank_zero_info + LIGHTNING_PACK_NAME = "lightning.pytorch." +except: + from pytorch_lightning import seed_everything + from pytorch_lightning.callbacks import Callback + from pytorch_lightning.trainer import Trainer + from pytorch_lightning.utilities import rank_zero_info + LIGHTNING_PACK_NAME = "pytorch_lightning." + +from ldm.data.base import Txt2ImgIterableBaseDataset +from ldm.util import instantiate_from_config + +import mlperf_logging_utils +import mlperf_logging.mllog.constants as mllog_constants +from mlperf_logging_utils import mllogger + + +def get_parser(**parser_kwargs): + # A function to create an ArgumentParser object and add arguments to it + + def str2bool(v): + # A helper function to parse boolean values from command line arguments + if isinstance(v, bool): + return v + if v.lower() in ("yes", "true", "t", "y", "1"): + return True + elif v.lower() in ("no", "false", "f", "n", "0"): + return False + else: + raise argparse.ArgumentTypeError("Boolean value expected.") + # Create an ArgumentParser object with specifies kwargs + parser = argparse.ArgumentParser(**parser_kwargs) + + # Add vairous command line arguments with their default balues and descriptions + parser.add_argument( + "-n", + "--name", + type=str, + const=True, + default="", + nargs="?", + help="postfix for logdir", + ) + parser.add_argument( + "-r", + "--resume", + type=str, + const=True, + default="", + nargs="?", + help="resume from logdir or checkpoint in logdir", + ) + parser.add_argument( + "-b", + "--base", + nargs="*", + metavar="base_config.yaml", + help="paths to base configs. Loaded from left-to-right. " + "Parameters can be overwritten or added with command-line options of the form `--key value`.", + default=list(), + ) + parser.add_argument( + "-m", + "--mode", + type=str, + default="train", + choices=["train", "validate"], + help="run mode, train or validation", + ) + parser.add_argument( + "-v", + "--validation", + type=str2bool, + const=True, + default=False, + nargs="?", + help="validation", + ) + parser.add_argument( + "-p", + "--project", + help="name of new or path to existing project", + ) + parser.add_argument( + "-c", + "--ckpt", + type=str, + const=True, + default="", + nargs="?", + help="load pretrained checkpoint from stable AI", + ) + parser.add_argument( + "-d", + "--debug", + type=str2bool, + nargs="?", + const=True, + default=False, + help="enable post-mortem debugging", + ) + parser.add_argument( + "-s", + "--seed", + type=int, + default=random.SystemRandom().randint(0, 2**32 - 1), + help="seed for seed_everything", + ) + parser.add_argument( + "--fid_threshold", + type=int, + default=90, + help="halt training once this FID validation score or a smaller one is achieved." + "if used with --clip_threshold, both metrics need to reach their targets.", + ) + parser.add_argument( + "--clip_threshold", + type=int, + default=0.15, + help="halt training once this CLIP validation score or a higher one is achieved." + "if used with --fid_threshold, both metrics need to reach their targets.", + ) + parser.add_argument( + "-f", + "--postfix", + type=str, + default="", + help="post-postfix for default name", + ) + parser.add_argument( + "-l", + "--logdir", + type=str, + default="/results", + help="directory for logging dat shit", + ) + parser.add_argument( + "--scale_lr", + type=str2bool, + nargs="?", + const=True, + default=True, + help="scale base-lr by ngpu * batch_size * n_accumulate", + ) + parser.add_argument( + "--train_log_interval", + type=int, + default=100, + help="Training logging interval" + ) + parser.add_argument( + "--validation_log_interval", + type=int, + default=10, + help="Validation logging interval" + ) + parser.add_argument( + "--hpus", + type=int, + default=0, + help="number of hpu devices to run", + ) + parser.add_argument( + "--use_lazy_mode", + type=lambda x: x.lower() == 'true', + default=True, + help="Run Lazy or Eager Mode on HPU, default: lazy", + ) + parser.add_argument( + "--batch_size", + type=int, + default=0, + help="batch size for training", + ) + parser.add_argument( + "--log_freq", + type=int, + default=50, + help="frequency of logging loss.", + ) + parser.add_argument( + "--autocast", dest="use_autocast", + action="store_true", + help="Use PyTorch autocast on Gaudi" + ) + parser.add_argument( + "--warmup", dest="warmup_path", + type=str, default=None, # Set a default value if needed + help="Path to the warmup dataset file" + ) + parser.add_argument( + "--async_checkpoint", dest='async_checkpoint', + action='store_true', + help="Enables usage of asynchronous checkpoint saving during training." + ) + parser.add_argument( + "--current_validation_iter", dest="current_validation_iter", + type=int, default=1, + help="Id of validation run" + ) + parser.add_argument( + "--validation_iters", dest="validation_iters", + type=int, default=5, + help="Number of all validation runs" + ) + return parser + +# A function that returns the non-default arguments between two objects +def nondefault_trainer_args(opt): + # create an argument parsser + parser = argparse.ArgumentParser() + # parse the empty arguments to obtain the default values + args = parser.parse_args([]) + # return all non-default arguments + return sorted(k for k in vars(args) if getattr(opt, k) != getattr(args, k)) + +class ListEarlyStopping(Callback): + # Early stopping class that accepts a list of metrics and all stopping_thresholds + # must be met before stopping + def __init__(self, monitor_metrics: list = ["validation/fid", "validation/clip"], + mode_metrics: dict = {'validation/fid': 'min', 'validation/clip': 'max'}, + stopping_thresholds: dict = {"validation/fid": None, "validation/clip": None}, + check_finite: bool = False): + super(ListEarlyStopping, self).__init__() + + self.monitor_metrics = monitor_metrics + self.mode_metrics = mode_metrics + self.stopping_thresholds = stopping_thresholds + self.check_finite = check_finite + + def check_metrics(self, current_metrics): + should_stop = [] + for metric in self.monitor_metrics: + if metric in current_metrics: + current_value = current_metrics[metric] + + if self.check_finite and not torch.isfinite(torch.as_tensor(current_value)): + raise ValueError(f"The monitored metric {metric} has become non-finite.") + + # Skip metrics without a stopping thresholds + if self.stopping_thresholds[metric] is None: + continue + + if self.mode_metrics[metric] == 'min': + should_stop.append(current_value <= self.stopping_thresholds[metric]) + + if self.mode_metrics[metric] == 'max': + should_stop.append(current_value >= self.stopping_thresholds[metric]) + + # A minimum of one metric should have been reviewed. + return False if not should_stop else all(should_stop) + + def on_validation_end(self, trainer, pl_module): + logs = trainer.callback_metrics + should_stop = self.check_metrics(logs) + if should_stop: + rank_zero_info('Early stopping conditioned have been met. Stopping training.') + trainer.should_stop = True + +class SetupCallback(Callback): + # I nitialize the callback with the necessary parameters + + def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config): + super().__init__() + self.resume = resume + self.now = now + self.logdir = logdir + self.ckptdir = ckptdir + self.cfgdir = cfgdir + self.config = config + self.lightning_config = lightning_config + + # Save a checkpoint if training is interrupted with keyboard interrupt + def on_keyboard_interrupt(self, trainer, pl_module): + if trainer.global_rank == 0: + print("Summoning checkpoint.") + ckpt_path = os.path.join(self.ckptdir, "last.ckpt") + # trainer.save_checkpoint(ckpt_path) + + # Create necessary directories and save configuration files before training starts + # def on_pretrain_routine_start(self, trainer, pl_module): + def on_fit_start(self, trainer, pl_module): + if trainer.global_rank == 0: + # Create logdirs and save configs + os.makedirs(self.logdir, exist_ok=True) + os.makedirs(self.ckptdir, exist_ok=True) + os.makedirs(self.cfgdir, exist_ok=True) + + print("Project config") + print(OmegaConf.to_yaml(self.config)) + OmegaConf.save(self.config, os.path.join(self.cfgdir, "{}-project.yaml".format(self.now))) + + # Save project config and lightning config as YAML files + print("Lightning config") + print(OmegaConf.to_yaml(self.lightning_config)) + OmegaConf.save(OmegaConf.create({"lightning": self.lightning_config}), + os.path.join(self.cfgdir, "{}-lightning.yaml".format(self.now))) + + # Remove log directory if resuming training and directory already exists + else: + # ModelCheckpoint callback created log directory --- remove it + if not self.resume and os.path.exists(self.logdir): + dst, name = os.path.split(self.logdir) + dst = os.path.join(dst, "child_runs", name) + os.makedirs(os.path.split(dst)[0], exist_ok=True) + try: + os.rename(self.logdir, dst) + except FileNotFoundError: + pass + + # def on_fit_end(self, trainer, pl_module): + # if trainer.global_rank == 0: + # ckpt_path = os.path.join(self.ckptdir, "last.ckpt") + # rank_zero_info(f"Saving final checkpoint in {ckpt_path}.") + # trainer.save_checkpoint(ckpt_path) + + +class CUDACallback(Callback): + # see https://github.com/SeanNaren/minGPT/blob/master/mingpt/callback.py + + def on_train_start(self, trainer, pl_module): + rank_zero_info("Training is starting") + + # the method is called at the end of each training epoch + def on_train_end(self, trainer, pl_module): + rank_zero_info("Training is ending") + + def on_train_epoch_start(self, trainer, pl_module): + # Reset the memory use counter + torch.cuda.reset_peak_memory_stats(trainer.strategy.root_device.index) + torch.cuda.synchronize(trainer.strategy.root_device.index) + self.start_time = time.time() + + def on_train_epoch_end(self, trainer, pl_module): + torch.cuda.synchronize(trainer.strategy.root_device.index) + max_memory = torch.cuda.max_memory_allocated(trainer.strategy.root_device.index) / 2**20 + epoch_time = time.time() - self.start_time + + try: + max_memory = trainer.strategy.reduce(max_memory) + epoch_time = trainer.strategy.reduce(epoch_time) + + rank_zero_info(f"Average Epoch time: {epoch_time:.2f} seconds") + rank_zero_info(f"Average Peak memory {max_memory:.2f}MiB") + except AttributeError: + pass + +class HPUCallback(Callback): + def on_train_start(self, trainer, pl_module): + rank_zero_info("Training is starting on HPU") + + # the method is called at the end of each training epoch + def on_train_end(self, trainer, pl_module): + rank_zero_info("Training is ending") + + def on_train_epoch_start(self, trainer, pl_module): + # Reset the memory use counter + torch.hpu.memory.reset_peak_memory_stats(trainer.strategy.root_device.index) + torch.hpu.synchronize() + self.start_time = time.time() + + def on_train_epoch_end(self, trainer, pl_module): + torch.hpu.synchronize() + max_memory = torch.hpu.memory.max_memory_allocated(trainer.strategy.root_device.index) / 2 ** 20 + epoch_time = time.time() - self.start_time + + try: + max_memory = trainer.strategy.reduce(max_memory) + epoch_time = trainer.strategy.reduce(epoch_time) + + rank_zero_info(f"Average Epoch time: {epoch_time:.2f} seconds") + rank_zero_info(f"Average Peak memory {max_memory:.2f} MiB") + except AttributeError: + pass + + +if __name__ == "__main__": + # custom parser to specify config files, train, test and debug mode, + # postfix, resume. + # `--key value` arguments are interpreted as arguments to the trainer. + # `nested.key=value` arguments are interpreted as config parameters. + # configs are merged from left-to-right followed by command line parameters. + + # model: + # base_learning_rate: float + # target: path to lightning module + # params: + # key: value + # data: + # target: main.DataModuleFromConfig + # params: + # batch_size: int + # wrap: bool + # train: + # target: path to train dataset + # params: + # key: value + # validation: + # target: path to validation dataset + # params: + # key: value + # test: + # target: path to test dataset + # params: + # key: value + # lightning: (optional, has sane defaults and can be specified on cmdline) + # trainer: + # additional arguments to trainer + # logger: + # logger to instantiate + # modelcheckpoint: + # modelcheckpoint to instantiate + # callbacks: + # callback1: + # target: importpath + # params: + # key: value + + parser = get_parser() + + opt, unknown = parser.parse_known_args() + + # get the current time to create a new logging directory + now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S") + + # add cwd for convenience and to make classes in this file available when + # running as `python main.py` + # (in particular `main.DataModuleFromConfig`) + sys.path.append(os.getcwd()) + + # Veirfy the arguments are both specified + if opt.name and opt.resume: + raise ValueError("-n/--name and -r/--resume cannot be specified both." + "If you want to resume training in a new log folder, " + "use -n/--name in combination with --resume_from_checkpoint") + + if opt.log_freq >= opt.train_log_interval: + raise ValueError("--log_freq should be lesser than --train_log_interval") + + # Check if the "resume" option is specified, resume training from the checkpoint if it is true + ckpt = None + if opt.resume: + rank_zero_info("Resuming from {}".format(opt.resume)) + if not os.path.exists(opt.resume): + raise ValueError("Cannot find {}".format(opt.resume)) + if os.path.isfile(opt.resume): + paths = opt.resume.split("/") + # idx = len(paths)-paths[::-1].index("logs")+1 + # logdir = "/".join(paths[:idx]) + logdir = "/".join(paths[:-2]) + rank_zero_info("logdir: {}".format(logdir)) + ckpt = opt.resume + else: + assert os.path.isdir(opt.resume), opt.resume + logdir = opt.resume.rstrip("/") + ckpt = os.path.join(logdir, "checkpoints", "last.ckpt") + + # Finds all ".yaml" configuration files in the log directory and adds them to the list of base configurations + base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*.yaml"))) + opt.base = base_configs + opt.base + # Gets the name of the current log directory by splitting the path and taking the last element. + _tmp = logdir.split("/") + nowname = _tmp[-1] + else: + if opt.name: + name = "_" + opt.name + elif opt.base: + rank_zero_info("Using base config {}".format(opt.base)) + cfg_fname = os.path.split(opt.base[0])[-1] + cfg_name = os.path.splitext(cfg_fname)[0] + name = "_" + cfg_name + else: + name = "" + nowname = now + name + opt.postfix + logdir = os.path.join(opt.logdir, nowname) + + # Sets the checkpoint path of the 'ckpt' option is specified + if opt.ckpt: + ckpt = opt.ckpt + + # Create the checkpoint and configuration directories within the log directory. + ckptdir = os.path.join(logdir, "checkpoints") + cfgdir = os.path.join(logdir, "configs") + # Sets the seed for the random number generator to ensure reproducibility + seed_everything(opt.seed) + + is_success = False + + # Read timestamp for current checkpoint + validation_timestamp = None + if opt.mode == "validate": + if os.path.exists(mllogger.filename): + with open(mllogger.filename, 'r') as mllog_file: + mllogs = mllog_file.readlines() + + step = opt.current_validation_iter * 1000 + for mllog in mllogs: + mllog = json.loads(mllog.replace(":::MLLOG ", "")) + if mllog["key"] == "checkpoint_saved" and mllog["metadata"]["step_num"] == step: + validation_timestamp = mllog["time_ms"] + break + + # Intinalize and save configuratioon using the OmegaConf library. + try: + # init and save configs + configs = [OmegaConf.load(cfg) for cfg in opt.base] + cli = OmegaConf.from_dotlist(unknown) + config = OmegaConf.merge(*configs, cli) + lightning_config = config.pop("lightning", OmegaConf.create()) + # merge trainer cli with config + trainer_config = lightning_config.get("trainer", OmegaConf.create()) + + for k in nondefault_trainer_args(opt): + trainer_config[k] = getattr(opt, k) + + if not opt.use_lazy_mode: + os.environ["PT_HPU_LAZY_MODE"] = "2" + if opt.hpus: + trainer_config["devices"] = opt.hpus + if opt.batch_size: + config.data.params.train.params.batch_size = opt.batch_size + + if trainer_config["accelerator"] == "hpu": + os.environ["PT_HPU_ENABLE_REFINE_DYNAMIC_SHAPES"] = "0" + os.environ["PT_HPU_POOL_MEM_ACQUIRE_PERC"] = "99" + os.environ["PT_ENABLE_INT64_SUPPORT"] = "true" + + # Check whether the accelerator is gpu or hpu + if not trainer_config["accelerator"] == "gpu" and not trainer_config["accelerator"] == "hpu": + del trainer_config["accelerator"] + cpu = True + else: + cpu = False + trainer_opt = argparse.Namespace(**trainer_config) + lightning_config.trainer = trainer_config + + # model + use_fp16 = trainer_config.get("precision", 32) == 16 + if use_fp16: + config.model["params"].update({"use_fp16": True}) + else: + config.model["params"].update({"use_fp16": False}) + + if ckpt is not None: + # If a checkpoint path is specified in the ckpt variable, the code updates the "ckpt" key in the "params" dictionary of the config.model configuration with the value of ckpt + config.model["params"].update({"ckpt": ckpt}) + rank_zero_info("Using ckpt_path = {}".format(config.model["params"]["ckpt"])) + if opt.use_autocast: + config.model.params.use_autocast = opt.use_autocast + + config.model.params.hpu = trainer_config["accelerator"] == "hpu" + model = instantiate_from_config(config.model) + + if opt.log_freq > 0: + model.log_freq = opt.log_freq + + # Configure gradient accumulation + if 'accumulate_grad_batches' in lightning_config.trainer: + accumulate_grad_batches = lightning_config.trainer.accumulate_grad_batches + else: + accumulate_grad_batches = 1 + lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches + + # Configure number of GPUs + if not cpu: + ngpu = trainer_config["devices"] * trainer_config["num_nodes"] + else: + ngpu = 1 + + # Configure batch size + local_batch_size = config.data.params.train.params.batch_size + global_batch_size = local_batch_size*ngpu + + # trainer and callbacks + trainer_kwargs = dict() + + # config the logger + # Default logger configs to log training metrics during the training process. + # These loggers are specified as targets in the dictionary, along with the configuration settings specific to each logger. + default_logger_cfgs = { + "wandb": { + "target": LIGHTNING_PACK_NAME + "loggers.WandbLogger", + "params": { + "name": nowname, + "save_dir": logdir, + "offline": opt.debug, + "id": nowname, + } + }, + "tensorboard": { + "target": LIGHTNING_PACK_NAME + "loggers.TensorBoardLogger", + "params": { + "save_dir": logdir, + "name": "diff_tb", + "log_graph": True + } + } + } + + # Set up the logger for TensorBoard + default_logger_cfg = default_logger_cfgs["tensorboard"] + if "logger" in lightning_config: + logger_cfg = lightning_config.logger + else: + logger_cfg = default_logger_cfg + logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg) + trainer_kwargs["logger"] = instantiate_from_config(logger_cfg) + + # config the strategy, defualt is ddp + if "strategy" in trainer_config: + strategy_cfg = trainer_config["strategy"] + strategy_cfg["target"] = LIGHTNING_PACK_NAME + strategy_cfg["target"] + else: + strategy_cfg = { + "target": LIGHTNING_PACK_NAME + "strategies.DDPStrategy", + "params": { + "find_unused_parameters": False + } + } + + if trainer_config["accelerator"] == "hpu": + if trainer_config["devices"] == 1: + from lightning_habana.pytorch.strategies import SingleHPUStrategy + from lightning_habana.pytorch.accelerator import HPUAccelerator + trainer_kwargs["strategy"] = SingleHPUStrategy() + trainer_kwargs["accelerator"] = HPUAccelerator() + elif trainer_config["devices"] > 1: + from lightning_habana.pytorch.strategies import HPUParallelStrategy + from lightning_habana.pytorch.accelerator import HPUAccelerator + parallel_hpus = [torch.device("hpu")] * trainer_config["devices"] + trainer_kwargs["strategy"] = HPUParallelStrategy(parallel_devices=parallel_hpus, + find_unused_parameters=False, gradient_as_bucket_view=True) + trainer_kwargs["accelerator"] = HPUAccelerator() + else: + trainer_kwargs["strategy"] = instantiate_from_config(strategy_cfg) + + # Set up various callbacks, including logging, learning rate monitoring, and CUDA management + # add callback which sets up log directory + default_callbacks_cfg = { + "setup_callback": { # callback to set up the training + "target": "main.SetupCallback", + "params": { + "resume": opt.resume, # resume training if applicable + "now": now, + "logdir": logdir, # directory to save the log file + "ckptdir": ckptdir, # directory to save the checkpoint file + "cfgdir": cfgdir, # directory to save the configuration file + "config": config, # configuration dictionary + "lightning_config": lightning_config, # LightningModule configuration + } + }, + "learning_rate_logger": { # callback to log learning rate + "target": "lightning.pytorch.callbacks.LearningRateMonitor", + "params": { + "logging_interval": "step", # logging frequency (either 'step' or 'epoch') + } + }, + "fid_clip_early_stop_callback" : { + "target": "main.ListEarlyStopping", + "params": { + "stopping_thresholds": {"validation/fid": opt.fid_threshold, "validation/clip": opt.clip_threshold}, + "check_finite": True + } + }, + } + if trainer_config["accelerator"] == "hpu": + default_callbacks_cfg["hpu_callback"] = {"target": "main.HPUCallback"} + elif trainer_config["accelerator"] == "gpu": + default_callbacks_cfg["cuda_callback"] = {"target": "main.CUDACallback"} + # If the LightningModule configuration has specified callbacks, use those + # Otherwise, create an empty OmegaConf configuration object + if "callbacks" in lightning_config: + callbacks_cfg = lightning_config.callbacks + else: + callbacks_cfg = OmegaConf.create() + + + # Merge the default callbacks configuration with the specified callbacks configuration, and instantiate the callbacks + callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg) + + trainer_kwargs["callbacks"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg] + trainer_kwargs["callbacks"].append(mlperf_logging_utils.MLPerfLoggingCallback(logger=mllogger, + train_log_interval=opt.train_log_interval, + validation_log_interval=opt.validation_log_interval, + validation_iter=opt.current_validation_iter, + validation_timestamp=validation_timestamp, + seed=opt.seed, + gradient_accumulation_steps=accumulate_grad_batches, + global_batch_size=global_batch_size)) + + # Set up ModelCheckpoint callback to save best models + # modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to + # specify which metric is used to determine best models + default_modelckpt_cfg = { + "target": LIGHTNING_PACK_NAME + "callbacks.ModelCheckpoint", + "params": { + "dirpath": ckptdir, + "filename": "{epoch:06}-{step:09}", + "verbose": True, + "save_last": True, + } + } + + if "modelcheckpoint" in lightning_config: + modelckpt_cfg = lightning_config.modelcheckpoint + else: + modelckpt_cfg = OmegaConf.create() + modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg) + trainer_kwargs["callbacks"].append(instantiate_from_config(modelckpt_cfg)) + + if opt.async_checkpoint: + from lightning.fabric.plugins import TorchCheckpointIO + from lightning.fabric.utilities import move_data_to_device + from concurrent.futures import ThreadPoolExecutor + + class CustomCheckpointIO(TorchCheckpointIO): + def save_checkpoint(self, checkpoint, path, storage_options=None): + if getattr(self, '_executor', None) is None: + self._executor = ThreadPoolExecutor(max_workers=1) + def _save_checkpoint(checkpoint, filepath) -> None: + torch.save(checkpoint, filepath) + + checkpoint = move_data_to_device(checkpoint, torch.device("cpu")) + + # log timestamp of current checkpoint + if "step" in path: + file_name = os.path.basename(path) + step_num = int(file_name.split("step=")[1].split('.')[0]) + mllogger.event(key="checkpoint_saved", metadata={mllog_constants.STEP_NUM: step_num}) + + self._executor.submit(_save_checkpoint, checkpoint, path) + + trainer_kwargs["plugins"] = [CustomCheckpointIO()] + + # Create a Trainer object with the specified command-line arguments and keyword arguments, and set the log directory + if opt.warmup_path is not None: + trainer_opt_copy = copy.deepcopy(trainer_opt) + trainer_opt_copy.max_steps=100 + trainer_opt_copy.max_epochs=1 + if "strategy" in trainer_opt_copy: + delattr(trainer_opt_copy, 'strategy') + trainer_warmup = Trainer(**vars(trainer_opt_copy), strategy=copy.deepcopy(trainer_kwargs["strategy"])) + if "logger" in trainer_kwargs: + delattr(trainer_opt, 'logger') + if "strategy" in trainer_kwargs: + delattr(trainer_opt, 'strategy') + if "accelerator" in trainer_kwargs: + delattr(trainer_opt, 'accelerator') + trainer = Trainer(**vars(trainer_opt), **trainer_kwargs) + trainer.logdir = logdir + # Create a data module based on the configuration file + data = instantiate_from_config(config.data) + + # Configure learning rate based on the batch size, base learning rate and number of GPUs + # If scale_lr is true, calculate the learning rate based on additional factors + base_lr = config.model.base_learning_rate + if opt.scale_lr: + model.learning_rate = accumulate_grad_batches * ngpu * local_batch_size * base_lr + rank_zero_info( + "Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (local_batch_size) * {:.2e} (base_lr)" + .format(model.learning_rate, accumulate_grad_batches, ngpu, local_batch_size, base_lr)) + else: + model.learning_rate = base_lr + rank_zero_info("++++ NOT USING LR SCALING ++++") + rank_zero_info(f"Setting learning rate to {model.learning_rate:.2e}") + + # Allow checkpointing via USR1 + def melk(*args, **kwargs): + # run all checkpoint hooks + if trainer.global_rank == 0: + print("Summoning checkpoint.") + ckpt_path = os.path.join(ckptdir, "last.ckpt") + trainer.save_checkpoint(ckpt_path) + + def divein(*args, **kwargs): + if trainer.global_rank == 0: + import pudb + pudb.set_trace() + + import signal + # Assign melk to SIGUSR1 signal and divein to SIGUSR2 signal + signal.signal(signal.SIGUSR1, melk) + signal.signal(signal.SIGUSR2, divein) + + # Run the training and validation + if opt.mode=="train": + try: + if opt.warmup_path is not None: + training_url = config.data.params.train.params.urls + config.data.params.train.params.urls = opt.warmup_path + # Warmup + trainer_warmup.fit(model, data) + # Actual training + config.data.params.train.params.urls = training_url + trainer.fit(model, data) + except Exception: + melk() + raise + elif opt.mode=="validate": + trainer.validate(model, data) + else: + raise ValueError(f"Unknown mode {opt.mode}") + + if opt.mode == "validate": + # Default is True in case thresholds are not defined + fid_success = True + clip_success = True + if opt.fid_threshold is not None: + fid_success = "validation/fid" in trainer.callback_metrics and opt.fid_threshold >= trainer.callback_metrics["validation/fid"].item() + if opt.clip_threshold is not None: + clip_success = "validation/clip" in trainer.callback_metrics and opt.clip_threshold <= trainer.callback_metrics["validation/clip"].item() + is_success = fid_success and clip_success + + except Exception: + # If there's an exception, debug it if opt.debug is true and the trainer's global rank is 0 + if opt.debug and trainer.global_rank == 0: + try: + import pudb as debugger + except ImportError: + import pdb as debugger + debugger.post_mortem() + raise + finally: + # Move the log directory to debug_runs if opt.debug is true and the trainer's global + if opt.debug and not opt.resume and trainer.global_rank == 0: + dst, name = os.path.split(logdir) + dst = os.path.join(dst, "debug_runs", name) + os.makedirs(os.path.split(dst)[0], exist_ok=True) + os.rename(logdir, dst) + if trainer.global_rank == 0: + print(trainer.profiler.summary()) + + if opt.mode == "validate": + is_last_run = opt.current_validation_iter == opt.validation_iters + if is_success or is_last_run: + mllogger.end( + mllog_constants.RUN_STOP, time_ms=validation_timestamp, + metadata={mllog_constants.STATUS: mllog_constants.SUCCESS if is_success else mllog_constants.ABORTED} + ) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/mlperf_logging_utils.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/mlperf_logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..94d4f2ec37d5da245e4b0e771391a1535e37e2cf --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/mlperf_logging_utils.py @@ -0,0 +1,201 @@ +import os +from typing import Any, Dict, Optional, Type + +from mlperf_logging import mllog +import mlperf_logging.mllog.constants as mllog_constants + +import torch +import torch.distributed as dist + +try: + import lightning.pytorch as pl + from lightning.pytorch.utilities.types import STEP_OUTPUT +except: + import pytorch_lightning as pl + from pytorch_lightning.utilities.types import STEP_OUTPUT + + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() + +def barrier(): + if not is_dist_avail_and_initialized(): + return + torch.distributed.barrier() + +class SDLogger: + def __init__(self, filename=None, default_stack_offset=2): + self.mllogger = mllog.get_mllogger() + self.filename = (filename or os.getenv("COMPLIANCE_FILE") or "mlperf_compliance.log") + mllog.config(default_stack_offset=default_stack_offset, filename=self.filename, + root_dir=os.path.normpath(os.path.dirname(os.path.realpath(__file__)))) + + @property + def rank(self): + return get_rank() + + def event(self, key, value=None, metadata=None, sync=False, time_ms=None): + if sync: + barrier() + if self.rank == 0: + self.mllogger.event(key=key, value=value, metadata=metadata, time_ms=time_ms) + + def start(self, key, value=None, metadata=None, sync=False, time_ms=None): + if sync: + barrier() + if self.rank == 0: + self.mllogger.start(key=key, value=value, metadata=metadata, time_ms=time_ms) + + def end(self, key, value=None, metadata=None, sync=False, time_ms=None): + if sync: + barrier() + if self.rank == 0: + self.mllogger.end(key=key, value=value, metadata=metadata, time_ms=time_ms) + +def submission_info(): + """Logs required for a valid MLPerf submission.""" + mllogger.event(key=mllog_constants.SUBMISSION_BENCHMARK, value=mllog_constants.STABLE_DIFFUSION) + mllogger.event(key=mllog_constants.SUBMISSION_DIVISION, value=mllog_constants.CLOSED) + mllogger.event(key=mllog_constants.SUBMISSION_ORG, value="reference_implementation") + mllogger.event(key=mllog_constants.SUBMISSION_PLATFORM, value="Gaudi2") + mllogger.event(key=mllog_constants.SUBMISSION_POC_NAME, value="") + mllogger.event(key=mllog_constants.SUBMISSION_POC_EMAIL, value="") + mllogger.event(key=mllog_constants.SUBMISSION_STATUS, value=mllog_constants.ONPREM) + +class MLPerfLoggingCallback(pl.callbacks.Callback): + def __init__(self, logger, train_log_interval=5, validation_log_interval=1, + validation_iter=1, validation_iters=5, validation_timestamp=None, + seed=None, gradient_accumulation_steps=None, global_batch_size=None): + super().__init__() + self.logger = logger + self.train_log_interval = train_log_interval + self.validation_log_interval = validation_log_interval + self.validation_iter = validation_iter + self.validation_iters = validation_iters + self.validation_timestamp = validation_timestamp + self.seed = seed + self.gradient_accumulation_steps = gradient_accumulation_steps + self.global_batch_size = global_batch_size + + def on_fit_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + submission_info() + + mllogger.event(key=mllog_constants.SEED, value=self.seed) + # We can't get number of samples without reading the data (which we can't inside the init block), so we hard code them + self.logger.event(key=mllog_constants.TRAIN_SAMPLES, value=1) # TODO(ahmadki): a placeholder until a dataset is picked + self.logger.event(key=mllog_constants.EVAL_SAMPLES, value=30000) + self.logger.event(mllog_constants.GRADIENT_ACCUMULATION_STEPS, value=self.gradient_accumulation_steps) + self.logger.event(mllog_constants.GLOBAL_BATCH_SIZE, value=self.global_batch_size) + self.logger.end(mllog_constants.INIT_STOP) + self.logger.start(mllog_constants.RUN_START) + + def on_fit_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + pass + + def on_train_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + pass + + def on_train_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + pass + + def on_train_epoch_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + pass + + def on_train_epoch_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + pass + + def on_train_batch_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", + batch: Any, batch_idx: int) -> None: + if trainer.global_step % self.train_log_interval == 0: + self.logger.start( + key=mllog_constants.BLOCK_START, value="training_step", + metadata={ + mllog_constants.EPOCH_COUNT: 1, + mllog_constants.FIRST_EPOCH_NUM: 0, + mllog_constants.STEP_NUM: trainer.global_step + } + ) + + def on_train_batch_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", + outputs: STEP_OUTPUT, batch: Any, batch_idx: int) -> None: + if trainer.global_step % self.train_log_interval == 0: + logs = trainer.callback_metrics + self.logger.event(key="loss", value=logs["train/loss"].item(), metadata={mllog_constants.STEP_NUM: trainer.global_step}) + self.logger.event(key="lr_abs", value=logs["lr_abs"].item(), metadata={mllog_constants.STEP_NUM: trainer.global_step}) + self.logger.end( + key=mllog_constants.BLOCK_STOP, value="training_step", + metadata={ + mllog_constants.FIRST_EPOCH_NUM: 0, + mllog_constants.STEP_NUM: trainer.global_step + } + ) + + def on_validation_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + self.logger.start( + key=mllog_constants.EVAL_START, value=trainer.global_step, time_ms=self.validation_timestamp, + metadata={ + mllog_constants.EPOCH_NUM: self.validation_iter, + mllog_constants.EPOCH_COUNT: self.validation_iters, + } + ) + + def on_validation_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + logs = trainer.callback_metrics + if "validation/fid" in logs: + self.logger.event( + key=mllog_constants.EVAL_ACCURACY, value=logs["validation/fid"].item(), time_ms=self.validation_timestamp, + metadata={ + mllog_constants.EPOCH_NUM: self.validation_iter, + mllog_constants.STEP_NUM: self.validation_iter * 1000, "metric": "FID" + } + ) + if "validation/clip" in logs: + self.logger.event( + key=mllog_constants.EVAL_ACCURACY, value=logs["validation/clip"].item(), time_ms=self.validation_timestamp, + metadata={ + mllog_constants.EPOCH_NUM: self.validation_iter, + mllog_constants.STEP_NUM: self.validation_iter * 1000, "metric": "CLIP" + } + ) + self.logger.end(key=mllog_constants.EVAL_STOP, value=trainer.global_step, + time_ms=self.validation_timestamp, metadata={mllog_constants.EPOCH_NUM: self.validation_iter}) + + def on_validation_epoch_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + pass + + def on_validation_epoch_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + pass + + def on_validation_batch_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", + batch: Any, batch_idx: int, dataloader_idx: int = 0) -> None: + if batch_idx % self.validation_log_interval == 0: + self.logger.start( + key=mllog_constants.BLOCK_START, value="validation_step", time_ms=self.validation_timestamp, + metadata={ + mllog_constants.STEP_NUM: batch_idx, + mllog_constants.EPOCH_COUNT: self.validation_iter, + mllog_constants.FIRST_EPOCH_NUM: self.validation_iter - 1, + } + ) + + def on_validation_batch_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", outputs: Optional[STEP_OUTPUT], + batch: Any, batch_idx: int, dataloader_idx: int = 0) -> None: + if batch_idx % self.validation_log_interval == 0: + self.logger.end( + key=mllog_constants.BLOCK_STOP, value="validation_step", time_ms=self.validation_timestamp, + metadata={ + mllog_constants.STEP_NUM: batch_idx, + mllog_constants.FIRST_EPOCH_NUM: self.validation_iter - 1, + } + ) + +mllogger = SDLogger() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/requirements.txt b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..7515b92cddb775828a4bfc230bd13c7aadac3c8b --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/requirements.txt @@ -0,0 +1,27 @@ +albumentations==1.3.0 +opencv-python==4.7.0.72 +pudb==2019.2 +prefetch_generator +imageio==2.9.0 +imageio-ffmpeg==0.4.2 +torchmetrics==0.11.4 +omegaconf==2.1.1 +test-tube>=0.7.5 +streamlit>=0.73.1 +einops==0.3.0 +transformers==4.19.2 +webdataset==0.2.5 +open-clip-torch==2.7.0 +gradio==3.11 +lightning==2.1.0 +lightning-habana==1.2.0 +titans==0.0.7 +datasets==2.10.1 +colossalai==0.2.7 +invisible-watermark==0.1.5 +diffusers==0.14.0 +img2dataset==1.41.0 +cloudpathlib==0.13.0 +bitsandbytes==0.37.2 +httpx==0.24.1 +git+https://github.com/mlcommons/logging.git@8405a08bbfc724f8888c419461c02d55a6ac960c diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/run_and_time.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/run_and_time.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a9a07ad65a1fe9df4ed205d1672e85b2b4b25c8 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/run_and_time.sh @@ -0,0 +1,64 @@ +#!/bin/bash + +: "${NUM_NODES:=1}" +: "${GPUS_PER_NODE:=8}" +: "${CHECKPOINT:=/checkpoints/sd/512-base-ema.ckpt}" +: "${RESULTS_DIR:=}" +: "${CONFIG:=./configs/train_512_latents.yaml}" + +while [ "$1" != "" ]; do + case $1 in + --num-nodes ) shift + NUM_NODES=$1 + ;; + --gpus-per-node ) shift + GPUS_PER_NODE=$1 + ;; + --checkpoint ) shift + CHECKPOINT=$1 + ;; + --results-dir ) shift + RESULTS_DIR=$1 + ;; + --config ) shift + CONFIG=$1 + ;; + esac + shift +done + +set -e + +export HF_DATASETS_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 +export DIFFUSERS_OFFLINE=1 +export HF_HOME=/hf_home + +start=$(date +%s) +start_fmt=$(date +%Y-%m-%d\ %r) +echo "STARTING TIMING RUN AT $start_fmt" + +# CLEAR YOUR CACHE HERE +python -c " +from mlperf_logging.mllog import constants +from mlperf_logging_utils import mllogger +mllogger.event(key=constants.CACHE_CLEAR, value=True)" + +python main.py \ + lightning.trainer.num_nodes=${NUM_NODES} \ + lightning.trainer.devices=${GPUS_PER_NODE} \ + -m train \ + --ckpt ${CHECKPOINT} \ + --logdir ${RESULTS_DIR} \ + -b ${CONFIG} + +# end timing +end=$(date +%s) +end_fmt=$(date +%Y-%m-%d\ %r) +echo "ENDING TIMING RUN AT $end_fmt" + +# runtime +runtime=$(( $end - $start )) +result_name="stable_diffusion" + +echo "RESULT,$result_name,$runtime,$USER,$start_fmt" diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/checkpoints/download_clip.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/checkpoints/download_clip.sh new file mode 100644 index 0000000000000000000000000000000000000000..148ebff7941cb4bb1b206755cd0f209c75319561 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/checkpoints/download_clip.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +: "${OUTPUT_DIR:=/checkpoints/clip}" + +while [ "$1" != "" ]; do + case $1 in + -o | --output-dir ) shift + OUTPUT_DIR=$1 + ;; + esac + shift +done + +CLIP_WEIGHTS_URL="https://huggingface.co/laion/CLIP-ViT-H-14-laion2B-s32B-b79K/resolve/main/open_clip_pytorch_model.bin" +CLIP_WEIGHTS_SHA256="9a78ef8e8c73fd0df621682e7a8e8eb36c6916cb3c16b291a082ecd52ab79cc4" + +CLIP_CONFIG_URL="https://huggingface.co/laion/CLIP-ViT-H-14-laion2B-s32B-b79K/raw/main/open_clip_config.json" + +wget -N -P ${OUTPUT_DIR} ${CLIP_WEIGHTS_URL} +wget -N -P ${OUTPUT_DIR} ${CLIP_CONFIG_URL} +echo "${CLIP_WEIGHTS_SHA256} ${OUTPUT_DIR}/open_clip_pytorch_model.bin" | sha256sum -c diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/checkpoints/download_inception.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/checkpoints/download_inception.sh new file mode 100644 index 0000000000000000000000000000000000000000..89e7146958faae147a1950940a8fd20a23a73ba2 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/checkpoints/download_inception.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +: "${OUTPUT_DIR:=/checkpoints/inception}" + +while [ "$1" != "" ]; do + case $1 in + -o | --output-dir ) shift + OUTPUT_DIR=$1 + ;; + esac + shift +done + +FID_WEIGHTS_URL='https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth' +FID_WEIGHTS_SHA1="bd836944fd6db519dfd8d924aa457f5b3c8357ff" + +wget -N -P ${OUTPUT_DIR} ${FID_WEIGHTS_URL} +echo "${FID_WEIGHTS_SHA1} ${OUTPUT_DIR}/pt_inception-2015-12-05-6726825d.pth" | sha1sum -c diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/checkpoints/download_sd.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/checkpoints/download_sd.sh new file mode 100644 index 0000000000000000000000000000000000000000..f8cef579e097d1622ee5deb15b68c43bbe85bc12 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/checkpoints/download_sd.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +: "${OUTPUT_DIR:=/checkpoints/sd}" + +while [ "$1" != "" ]; do + case $1 in + -o | --output-dir ) shift + OUTPUT_DIR=$1 + ;; + esac + shift +done + +SD_WEIGHTS_URL='https://huggingface.co/stabilityai/stable-diffusion-2-base/resolve/main/512-base-ema.ckpt' +SD_WEIGHTS_SHA256="d635794c1fedfdfa261e065370bea59c651fc9bfa65dc6d67ad29e11869a1824" + +wget -N -P ${OUTPUT_DIR} ${SD_WEIGHTS_URL} +echo "${SD_WEIGHTS_SHA256} ${OUTPUT_DIR}/512-base-ema.ckpt" | sha256sum -c diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/coco-2014-validation-download.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/coco-2014-validation-download.sh new file mode 100644 index 0000000000000000000000000000000000000000..ca834bc2228077d806b3f4a3d10fe4c6c57bbbd8 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/coco-2014-validation-download.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +: "${DOWNLOAD_PATH:=/datasets/coco2014}" + +while [ "$1" != "" ]; do + case $1 in + -d | --download-path ) shift + DOWNLOAD_PATH=$1 + ;; + esac + shift +done + +mkdir -p ${DOWNLOAD_PATH} +cd ${DOWNLOAD_PATH} + +wget -c http://images.cocodataset.org/zips/val2014.zip +wget -c http://images.cocodataset.org/annotations/annotations_trainval2014.zip + +echo "fbedd73593f242db65cce6bcefde193fcedcc5c0 ./val2014.zip" | sha1sum -c +echo "8e0b9df54c175f1688400e98d1a97f292e726870 ./annotations_trainval2014.zip" | sha1sum -c + +unzip val2014.zip +unzip annotations_trainval2014.zip diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/coco-split-resize.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/coco-split-resize.py new file mode 100644 index 0000000000000000000000000000000000000000..b2c99beb3410e99fad7d6464aed2025520f6dba4 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/coco-split-resize.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 + +import os +import json +import argparse +from concurrent.futures import ProcessPoolExecutor + +import pandas as pd +from PIL import Image + + +parser = argparse.ArgumentParser() +parser.add_argument("--input-images-dir", type=str, required=True) +parser.add_argument("--input-captions-file", type=str, required=True) +parser.add_argument("--output-images-dir", type=str, required=True) +parser.add_argument("--output-tsv-file", type=str, required=True) +parser.add_argument("--num-samples", type=int, default=30000) +parser.add_argument("--seed", type=int, default=2023) +parser.add_argument("--width", type=int, default=512) +parser.add_argument("--height", type=int, default=512) +parser.add_argument("--num-workers", type=int, default=4) +parser.add_argument("--allow-duplicate-images", type=bool, default=False) + +args = parser.parse_args() + + +def resize_image(input_image, output_image, width, height, resample=Image.Resampling.BICUBIC): + print(f"{input_image} -> {output_image}") + image = Image.open(input_image) + image = image.resize((width, height), resample=resample) + image.save(output_image) + + +# Load coco annotations +with open(args.input_captions_file, "r") as f: + captions = json.load(f) + annotations = captions["annotations"] + +# Convert to dataframe +df = pd.DataFrame(annotations) +df['caption'] = df['caption'].apply(lambda x: x.replace('\n', '').strip()) + +# Shuffle the dataframe +df = df.sample(frac=1, random_state=args.seed).reset_index(drop=True) + +# Keep a single captions per image +if not args.allow_duplicate_images: + df = df.drop_duplicates(subset=["image_id"], keep="first") + +# Take a subset +df = df[:args.num_samples] + +# Sort by id +df = df.sort_values(by=["id"]) + +# Save the subset to a tsv file +df.to_csv(args.output_tsv_file, sep="\t", index=False) + +# Create output image directory if it doesn't exist +os.makedirs(args.output_images_dir, exist_ok=True) + +# resize images with a worker pool +with ProcessPoolExecutor(max_workers=args.num_workers) as executor: + for i, row in df.iterrows(): + image_fname = f"COCO_val2014_{row['image_id']:012}.jpg" + input_img = os.path.join(args.input_images_dir, image_fname) + output_img = os.path.join(args.output_images_dir, image_fname) + + executor.submit(resize_image, input_img, output_img, args.width, args.height, Image.Resampling.BICUBIC) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/coco2014-validation-download-prompts.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/coco2014-validation-download-prompts.sh new file mode 100644 index 0000000000000000000000000000000000000000..9fd4b01e10d3dd623f2c5c04daf74052ca6ee33f --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/coco2014-validation-download-prompts.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +: "${OUTPUT_DIR:=/datasets/coco2014}" + +while [ "$1" != "" ]; do + case $1 in + -o | --output-dir ) shift + OUTPUT_DIR=$1 + ;; + esac + shift +done + +mkdir -p ${OUTPUT_DIR} +wget -O ${OUTPUT_DIR}/val2014_30k.tsv -c "https://cloud.mlcommons.org/index.php/s/training_stable_diffusion/download?path=/datasets/coco2014&files=val2014_30k.tsv" diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/filter-metadata.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/filter-metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..9aeef19a222a7bcd17a911ebd9d215f0bada69d9 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/filter-metadata.py @@ -0,0 +1,38 @@ +import os +import pandas as pd +import argparse +from pathlib import Path +from tqdm import tqdm + +def filter_parquet_files(input_folder, output_folder): + # Create output directory if it does not exist + os.makedirs(output_folder, exist_ok=True) + + # Get list of all parquet files in each directory + parquet_files = [f for f in os.listdir(input_folder) if f.endswith('.parquet')] + + # Iterate over all the files in the input folder, filter out rows where LICENSE column has a value of "?" + for file in parquet_files: + df = pd.read_parquet(os.path.join(input_folder, file)) + df_filtered = df[df['LICENSE'] != '?'] + + print(f'{file}: Original samples = {len(df)}, Samples after LICENSE filtering = {len(df_filtered)}') + + output_path = os.path.join(output_folder, file) + df_filtered.to_parquet(output_path) + + +def parse_arguments(): + parser = argparse.ArgumentParser(description='Filter parquet files.') + parser.add_argument('--input-folder', required=True, help='Path to the input folder.') + parser.add_argument('--output-folder', required=True, help='Path to the output folder.') + return parser.parse_args() + + +def main(): + args = parse_arguments() + filter_parquet_files(args.input_folder, args.output_folder) + + +if __name__ == '__main__': + main() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/generate-fid-statistics.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/generate-fid-statistics.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff49e3bc8441e8878b7e20c8c4b1a66ed37062d4 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/generate-fid-statistics.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +: "${DATASET_DIR:=/datasets/coco2014/val2014_512x512_30k}" +: "${OUTPUT_FILE:=/datasets/coco2014/val2014_512x512_30k_stats.npz}" + +while [ "$1" != "" ]; do + case $1 in + -d | --dataset-dir ) shift + DATASET_DIR=$1 + ;; + -o | --output-file ) shift + OUTPUT_FILE=$1 + ;; + esac + shift +done + +python ldm/modules/fid/fid_score.py --save-stats ${DATASET_DIR} ${OUTPUT_FILE} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-convert-images-to-moments.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-convert-images-to-moments.sh new file mode 100644 index 0000000000000000000000000000000000000000..150371757a247b6559f927d2cb6e1e41358bc017 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-convert-images-to-moments.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +: "${INPUT_FOLDER:=/datasets/laion-400m/webdataset-filtered}" +: "${OUTPUT_FOLDER:=/datasets/laion-400m/webdataset-latents-filtered}" + +while [ "$1" != "" ]; do + case $1 in + -i | --input-folder ) shift + INPUT_FOLDER=$1 + ;; + -o | --output-folder ) shift + OUTPUT_FOLDER=$1 + ;; + esac + shift +done + +mkdir -p ${OUTPUT_FOLDER} + +# Loop over each tar file in the input directory +for tar_file in ${INPUT_FOLDER}/*.tar; do + file_name=$(basename "$tar_file") + base_name="${file_name%.*}" + python webdataset_images2latents.py \ + --input-tar ${tar_file} \ + --output-tar ${OUTPUT_FOLDER}/${base_name}.tar \ + --config configs/train_512.yaml \ + --ckpt /checkpoints/sd/512-base-ema.ckpt +done diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-download-dataset.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-download-dataset.sh new file mode 100644 index 0000000000000000000000000000000000000000..707ef41240ba21b76b008bd908b94770aae43934 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-download-dataset.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash + +: "${NPROCS:=16}" +: "${NTHREADS:=64}" +: "${METADATA_DIR:=/datasets/laion-400m/metadata-filtered}" +: "${OUTPUT_DIR:=/datasets/laion-400m/webdataset-filtered}" + +while [ "$1" != "" ]; do + case $1 in + -j | --processes ) shift + NPROCS=$1 + ;; + -t | --threads ) shift + NTHREADS=$1 + ;; + -m | --metadata-dir ) shift + METADATA_DIR=$1 + ;; + -o | --output-dir ) shift + OUTPUT_DIR=$1 + ;; + esac + shift +done + +mkdir -p ${OUTPUT_DIR} + +img2dataset \ + --url_list ${METADATA_DIR} \ + --input_format "parquet" \ + --url_col "URL" \ + --caption_col "TEXT" \ + --output_format webdataset \ + --output_folder ${OUTPUT_DIR} \ + --processes_count ${NPROCS} \ + --thread_count ${NTHREADS} \ + --incremental_mode "incremental" \ + --resize_mode "no" \ + --save_additional_columns '["SAMPLE_ID","LICENSE","NSFW","similarity","WIDTH","HEIGHT"]' \ + --enable_wandb False diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-download-metadata.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-download-metadata.sh new file mode 100644 index 0000000000000000000000000000000000000000..372c86065244c61bbc5dd9de42bed3a90d8da4c3 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-download-metadata.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +: "${OUTPUT_DIR:=/datasets/laion-400m/metadata}" + +while [ "$1" != "" ]; do + case $1 in + -o | --output-dir ) shift + OUTPUT_DIR=$1 + ;; + esac + shift +done + +mkdir -p ${OUTPUT_DIR} + +for i in {00000..00031}; do wget -N -P ${OUTPUT_DIR} https://the-eye.eu/public/AI/cah/laion400m-met-release/laion400m-meta/part-$i-5b54c5d5-bbcf-484d-a2ce-0d6f73df1a36-c000.snappy.parquet; done diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-filter-metadata.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-filter-metadata.sh new file mode 100644 index 0000000000000000000000000000000000000000..dd1646ffa5d5b244fed5e46d95a32a00e5b13992 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-filter-metadata.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +: "${INPUT_METADATA_DIR:=/datasets/laion-400m/metadata}" +: "${OUTPUT_METADATA_DIR:=/datasets/laion-400m/metadata-filtered}" + +while [ "$1" != "" ]; do + case $1 in + -i | --input-metadata-dir ) shift + INPUT_METADATA_DIR=$1 + ;; + -o | --output-metadata-dir ) shift + OUTPUT_METADATA_DIR=$1 + ;; + esac + shift +done + +mkdir -p ${OUTPUT_METADATA_DIR} + +python scripts/datasets/filter-metadata.py \ + --input-folder ${INPUT_METADATA_DIR} \ + --output-folder ${OUTPUT_METADATA_DIR} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-filtered-download-images.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-filtered-download-images.sh new file mode 100644 index 0000000000000000000000000000000000000000..335e0a56fccc8f2bc77632b84c0b7561b36d1a6a --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-filtered-download-images.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +: "${OUTPUT_DIR:=/datasets/laion-400m/webdataset-filtered}" + +while [ "$1" != "" ]; do + case $1 in + -o | --output-dir ) shift + OUTPUT_DIR=$1 + ;; + esac + shift +done + +mkdir -p ${OUTPUT_DIR} +cd ${OUTPUT_DIR} + + +for i in {00000..00831}; do wget -O ${OUTPUT_DIR}/${i}.tar -c "https://cloud.mlcommons.org/index.php/s/training_stable_diffusion/download?path=/datasets/laion-400m/images-webdataset-filtered&files=${i}.tar"; done + +wget -O ${OUTPUT_DIR}/sha512sums.txt -c "https://cloud.mlcommons.org/index.php/s/training_stable_diffusion/download?path=/datasets/laion-400m/images-webdataset-filtered&files=sha512sums.txt" + +sha512sum --quiet -c sha512sums.txt diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-filtered-download-moments.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-filtered-download-moments.sh new file mode 100644 index 0000000000000000000000000000000000000000..ebedef98d6d1e0cf06871744a7719564cf65e6ba --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/datasets/laion400m-filtered-download-moments.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +: "${OUTPUT_DIR:=/datasets/laion-400m/webdataset-moments-filtered}" + +while [ "$1" != "" ]; do + case $1 in + -o | --output-dir ) shift + OUTPUT_DIR=$1 + ;; + esac + shift +done + +mkdir -p ${OUTPUT_DIR} +cd ${OUTPUT_DIR} + + +for i in {00000..00831}; do wget -O ${OUTPUT_DIR}/${i}.tar -c "https://cloud.mlcommons.org/index.php/s/training_stable_diffusion/download?path=/datasets/laion-400m/moments-webdataset-filtered&files=${i}.tar"; done + +wget -O ${OUTPUT_DIR}/sha512sums.txt -c "https://cloud.mlcommons.org/index.php/s/training_stable_diffusion/download?path=/datasets/laion-400m/moments-webdataset-filtered&files=sha512sums.txt" + +sha512sum --quiet -c sha512sums.txt diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/docker/build.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/docker/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..ce12020d058300ffcfadbda342f6cff8a3c8610d --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/docker/build.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +: "${SRC_IMG:=nvcr.io/nvidia/pytorch:22.12-py3}" +: "${DST_IMG:=mlperf_sd:22.12-py3}" + +while [ "$1" != "" ]; do + case $1 in + -s | --src-img ) shift + SRC_IMG=$1 + ;; + -d | --dst-img ) shift + DST_IMG=$1 + ;; + esac + shift +done + +docker build -f Dockerfile . --rm -t ${DST_IMG} --build-arg FROM_IMAGE_NAME=${SRC_IMG} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/docker/launch.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/docker/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..2c074d1f1fc52f49bb7e21176d5ee3c99f2d9b53 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/docker/launch.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +: "${DST_IMG:=mlperf_sd:22.12-py3}" + +while [ "$1" != "" ]; do + case $1 in + -d | --dst-img ) shift + DST_IMG=$1 + ;; + esac + shift +done + +docker run --rm -it --gpus=all --ipc=host \ + -e PYTHONPYCACHEPREFIX=/tmp/.pycache \ + --workdir /pwd \ + -v ${PWD}:/pwd \ + -v /datasets/laion-400m:/datasets/laion-400m \ + -v /datasets/coco2014:/datasets/coco2014 \ + -v /checkpoints:/checkpoints \ + -v /results:/results \ + ${DST_IMG} bash diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/prepare_synthetic_data.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/prepare_synthetic_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e9a66718476271b7da21f915bf922ce600e9ebb7 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/prepare_synthetic_data.py @@ -0,0 +1,71 @@ +"""Utility to generate the synthetic dataset""" +import os +import string +import random +import json +import numpy as np + + +input_path = os.environ.get('DATASET_PATH_UNCOMPRESSED') +output_path = os.environ.get('DATASET_PATH_OUTPUT') + +if not os.path.exists(output_path): + os.makedirs(output_path) + print(f"Directory '{output_path}' created successfully.") +else: + print(f"Directory '{output_path}' already exists.") + +all_files = os.listdir(input_path) + +# Filter for files with the .npy suffix +npy_files = [file for file in all_files if file.endswith('.npy')] + +INDEX =1 +num_of_files = len(npy_files) +for file in npy_files: + file_name = file[:-4] + print(f"{file_name} is {INDEX} out of {num_of_files} files \n") + INDEX = INDEX + 1 + input_file_path=input_path+'/'+ file_name + output_file_path = output_path+'/'+file_name + + # Modify the json file + try: + input_json_file_path = input_file_path + '.json' + output_json_file_path = output_file_path + '.json' + + caption_length = random.randint(5, 20) + with open(input_json_file_path, 'r') as input_json_file: + data = json.load(input_json_file) + data['url'] = 'synthetic_data' + data['caption']= ' '.join(random.choice(string.ascii_letters + string.digits) \ + for _ in range(caption_length)) + with open(output_json_file_path, 'w') as output_json_file: + json.dump(data, output_json_file) + + input_json_file.close() + output_json_file.close() + + except Exception as e: + print(f"An error occurred: {e}") + + # Modify the output txt file + try: + output_txt_file_path = output_file_path + '.txt' + + with open(output_txt_file_path, 'w') as text_file: + # Write the string to the file + text_file.write(data['caption']) + + except Exception as e: + print(f"An error occurred: {e}") + + # Modify the numpy file + try: + input_npy_file_path = input_file_path+'.npy' + output_npy_file_path = output_file_path+'.npy' + data = np.load(input_npy_file_path) + random_array = np.random.randn(*data.shape).astype(np.float32) + np.save(output_npy_file_path, random_array) + except Exception as e: + print(f"An error occurred: {e}") diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/prepare_synthetic_data.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/prepare_synthetic_data.sh new file mode 100644 index 0000000000000000000000000000000000000000..3db651aed7d262e1fd89a8f29995b48191e7452d --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/prepare_synthetic_data.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# + +if [ -n "${DATASET_PATH_UNCOMPRESSED+x}" ] && [ -d "$DATASET_PATH_UNCOMPRESSED" ]; then + if [ -n "${DATASET_PATH_OUTPUT+x}" ] && [ -d "$DATASET_PATH_OUTPUT" ]; then + python prepare_synthetic_data.py + fi +else + export DATASET_PATH_UNCOMPRESSED=/tmp/input/ + export DATASET_PATH_OUTPUT=/tmp/output + python prepare_synthetic_data.py +fi + +cd $DATASET_PATH_OUTPUT +tar -cvf SD_synthetic_data_10001.tar * diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/run_init.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/run_init.sh new file mode 100644 index 0000000000000000000000000000000000000000..e6de3890fbeb0721b03650da1eb24436d7aa5d11 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/run_init.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +# Clear caches +PROC_FS=${PROC_FS:-"/proc"} +sync && echo 3 > $PROC_FS/sys/vm/drop_caches + +#Add timestamp per worker for init +python3 -c " +import mlperf_logging.mllog.constants as mllog_constants +from mlperf_logging_utils import mllogger +mllogger.event(key=mllog_constants.CACHE_CLEAR, value=True) +mllogger.start(key=mllog_constants.INIT_START) +" diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/slurm/sbatch.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/slurm/sbatch.sh new file mode 100644 index 0000000000000000000000000000000000000000..961fbae010c9e0903ed1fba5927282b5d0f2d6cd --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/slurm/sbatch.sh @@ -0,0 +1,103 @@ +#!/bin/bash + +: "${NUM_NODES:=8}" +: "${GPUS_PER_NODE:=8}" +: "${WALLTIME:=04:00:00}" +: "${CONFIG:=./configs/train_512_latents.yaml}" +: "${BASE_LOG_DIR:=./nogit/logs}" +: "${BASE_RESULTS_DIR:=/results}" +: "${JOB_NAME:=job}" +: "${CONTAINER_IMAGE:=mlperf_sd:22.12-py3}" +: "${CHECKPOINT:=/checkpoints/sd/512-base-ema.ckpt}" +: "${ACCOUNT:=account}" +: "${PARTITION:=partition}" + +while [ "$1" != "" ]; do + case $1 in + -a | --account ) shift + ACCOUNT=$1 + ;; + -p | --partition ) shift + PARTITION=$1 + ;; + -n | --num-nodes ) shift + NUM_NODES=$1 + ;; + -g | --gpus-per-node ) shift + GPUS_PER_NODE=$1 + ;; + -t | --walltime ) shift + WALLTIME=$1 + ;; + -c | --config ) shift + CONFIG=$1 + ;; + -k | --checkpoint ) shift + CHECKPOINT=$1 + ;; + -l | --log-dir ) shift + BASE_LOG_DIR=$1 + ;; + -r | --results-dir ) shift + BASE_RESULTS_DIR=$1 + ;; + -d | --container ) shift + CONTAINER_IMAGE=$1 + ;; + esac + shift +done + +# Misc +SUFFIX=`date +%s` +CONFIG_NAME=`basename ${CONFIG} .yaml` +WORKDIR_MNT=/workdir + +# Job config +JOB_NAME=train_${CONFIG_NAME}_${SUFFIX} + + +# Laion 400m +LAION_400M=/datasets/laion-400m +LAION_400M_MOUNT=/datasets/laion-400m + +# COCO +COCO=/datasets/coco2014 +COCO_MNT=/datasets/coco2014 + +# checkpoints +CKPT_DIR=/checkpoints +CKPT_MOUNT=/checkpoints + +# Hugging face home +HF_HOME_DIR=/hf_home +HF_HOME_MOUNT=/hf_home + +# exp +RESULTS_DIR=${BASE_RESULTS_DIR} # no need to append job name, pytorch appends datetime automatically +RESULTS_MNT=/results +mkdir -p ${RESULTS_DIR} + +# logdir +LOG_DIR="${BASE_LOG_DIR}" +mkdir -p ${LOG_DIR} + +# Mounts +MOUNTS="${PWD}:${WORKDIR_MNT},${LAION_400M}:${LAION_400M_MOUNT},${COCO}:${COCO_MNT},${RESULTS_DIR}:${RESULTS_MNT},${CKPT_DIR}:${CKPT_MOUNT},${HF_HOME_DIR}:${HF_HOME_MOUNT}" +sbatch \ + --account=${ACCOUNT} \ + --partition=${PARTITION} \ + --job-name="mlperf-ssd:${JOB_NAME}" \ + --nodes="${NUM_NODES}" \ + --ntasks-per-node="${GPUS_PER_NODE}" \ + --time="${WALLTIME}" \ + --output="${LOG_DIR}/%A_${JOB_NAME}.out" \ + ./scripts/slurm/srun.sh \ + --num-nodes ${NUM_NODES} \ + --gpus-per-node ${GPUS_PER_NODE} \ + --config ${CONFIG} \ + --workdir ${WORKDIR_MNT} \ + --results-dir ${RESULTS_MNT} \ + --mounts ${MOUNTS} \ + --container ${CONTAINER_IMAGE} \ + --checkpoint ${CHECKPOINT} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/slurm/srun.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/slurm/srun.sh new file mode 100644 index 0000000000000000000000000000000000000000..56309a0723e8c576ba6ee391d6daaf5c39920f63 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/slurm/srun.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash + +: "${NUM_NODES:=8}" +: "${GPUS_PER_NODE:=8}" +: "${CONFIG:=./configs/train_512_latents.yaml}" +: "${WORKDIR:=/workdir}" +: "${RESULTS_MNT:=/results}" +: "${MOUNTS:=}" +: "${CONTAINER_IMAGE:=mlperf_sd:22.12-py3}" +: "${CHECKPOINT:=/checkpoints/sd/512-base-ema.ckpt}" + +while [ "$1" != "" ]; do + case $1 in + --num-nodes ) shift + NUM_NODES=$1 + ;; + --gpus-per-node ) shift + GPUS_PER_NODE=$1 + ;; + --config ) shift + CONFIG=$1 + ;; + --checkpoint ) shift + CHECKPOINT=$1 + ;; + --workdir ) shift + WORKDIR=$1 + ;; + --results-dir ) shift + RESULTS_MNT=$1 + ;; + --mounts ) shift + MOUNTS=$1 + ;; + --container ) shift + CONTAINER_IMAGE=$1 + ;; + esac + shift +done + +srun \ + --container-image="${CONTAINER_IMAGE}" \ + --container-mounts="${MOUNTS}" \ + --container-workdir="${WORKDIR}" \ + --ntasks-per-node="${GPUS_PER_NODE}" \ + --nodes="${NUM_NODES}" \ + bash -c "./run_and_time.sh \ + --num-nodes ${NUM_NODES} \ + --gpus-per-node ${GPUS_PER_NODE} \ + --checkpoint ${CHECKPOINT} \ + --results-dir ${RESULTS_MNT} \ + --config ${CONFIG}" diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/train.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/train.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c61cf83a4d61fa51c007a4bd75912d95a52314d --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/scripts/train.sh @@ -0,0 +1,8 @@ +HF_DATASETS_OFFLINE=1 +TRANSFORMERS_OFFLINE=1 +DIFFUSERS_OFFLINE=1 + +python main.py -m train \ + --logdir /tmp/results \ + --autocast \ + -b ./configs/train_512.yaml diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/webdataset_images2latents.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/webdataset_images2latents.py new file mode 100644 index 0000000000000000000000000000000000000000..4e3ba0fc686995ea61e5dbd86c1a7258ed25ee23 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/stable_diffusion/webdataset_images2latents.py @@ -0,0 +1,94 @@ +import os +import tarfile +import argparse +import tempfile + +import numpy as np +from PIL import Image +from tqdm import tqdm +from omegaconf import OmegaConf +import torch +import torchvision +from torchvision import transforms + +from ldm.data.utils import rearrange_transform +from ldm.util import instantiate_from_config + +Image.MAX_IMAGE_PIXELS = None + + +image_extensions = [".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tiff", ".ico"] + +def is_image(filename): + return any(filename.endswith(ext) for ext in image_extensions) + + +def process_image(input_image_path, output_tensor_name, image_transforms, model): + original_image = Image.open(input_image_path).convert('RGB') + transformed_img = image_transforms(original_image).float().unsqueeze(0).to(model.device) + moments = model.moments_first_stage(transformed_img) + np.save(output_tensor_name, moments.to("cpu").numpy()) + + +def process_tar(input_tar, output_tar, image_transforms, model): + with tempfile.TemporaryDirectory() as tempdir: + # Extract the input tar into a temporary folder + with tarfile.open(input_tar, 'r') as tar: + tar.extractall(path=tempdir) + + # Walk through all the files in the directory + for subdir, dirs, files in os.walk(tempdir): + for file in tqdm(files, desc=f'Processing files', unit='file'): + file_path = os.path.join(subdir, file) + if is_image(file_path): + file_path_without_ext = os.path.splitext(file_path)[0] + process_image(file_path, file_path_without_ext + '.npy', image_transforms, model) + os.remove(file_path) # remove the original image file + + # Recreate the tarfile with the modified images. + # for atomicity, we first create a temp tar then rename it + temp_tar_file = output_tar + '.tmp' + with tarfile.open(temp_tar_file, 'w') as tar: + tar.add(tempdir, arcname='') + os.rename(temp_tar_file, output_tar) + + +def load_model_from_config(config, ckpt, verbose=False): + print(f"Loading model from {ckpt}") + pl_sd = torch.load(ckpt, map_location="cpu") + sd = pl_sd["state_dict"] + print(f"instantiate_from_config") + model = instantiate_from_config(config.model) + m, u = model.load_state_dict(sd, strict=False) + if len(m) > 0 and verbose: + print("missing keys:") + print(m) + if len(u) > 0 and verbose: + print("unexpected keys:") + print(u) + + return model + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Process and resize images in tar files.') + parser.add_argument('--input-tar', required=True, help='Input tar file') + parser.add_argument('--output-tar', required=True, help='Output tar file') + parser.add_argument('--config', required=True, help='The model config') + parser.add_argument('--ckpt', required=True, help='The model config') + parser.add_argument('--resolution', default=512, help='Output image resolution') + + args = parser.parse_args() + device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") + + # Image transform + image_transforms = transforms.Compose([ + torchvision.transforms.ToTensor(), # (H x W x C) -> (C x H x W). + torchvision.transforms.Resize(size=args.resolution, interpolation=transforms.InterpolationMode.BICUBIC), + torchvision.transforms.CenterCrop(size=args.resolution), + ]) + + config = OmegaConf.load(args.config) + model = load_model_from_config(config, args.ckpt).to(device) + + process_tar(args.input_tar, args.output_tar, image_transforms, model)