Files
paddlepaddle--paddle/test/auto_parallel/test_utils.py
T
2026-07-13 12:40:42 +08:00

98 lines
3.0 KiB
Python

# Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import paddle
import paddle.distributed as dist
from paddle import nn
from paddle.distributed import Replicate, Shard
from paddle.io import DataLoader
BATCH_SIZE = 4
BATCH_NUM = 40
IMAGE_SIZE = 16
CLASS_NUM = 8
np.random.seed(2024)
paddle.seed(2024)
class RandomDataset(paddle.io.Dataset):
def __init__(self, images, labels, num_samples):
self.images = images
self.labels = labels
self.num_samples = num_samples
def __getitem__(self, idx):
return self.images[idx], self.labels[idx]
def __len__(self):
return self.num_samples
class DemoNet(nn.Layer):
def __init__(self, mesh, shard=True):
super().__init__()
self._mesh = mesh
self.linear_0 = nn.Linear(IMAGE_SIZE, IMAGE_SIZE, bias_attr=False)
self.linear_1 = nn.Linear(IMAGE_SIZE, CLASS_NUM, bias_attr=False)
self.relu_0 = nn.ReLU()
self.relu_1 = nn.ReLU()
self.relu_2 = nn.ReLU()
self.shard = shard
# shard the weights of this layer
if self.shard:
self.linear_0.weight = dist.shard_tensor(
self.linear_0.weight,
self._mesh,
[Shard(1)],
stop_gradient=False,
)
self.linear_1.weight = dist.shard_tensor(
self.linear_1.weight,
self._mesh,
[Shard(0)],
stop_gradient=False,
)
else:
self.linear_0.weight = dist.shard_tensor(
self.linear_0.weight,
self._mesh,
[Replicate()],
stop_gradient=False,
)
self.linear_1.weight = dist.shard_tensor(
self.linear_1.weight,
self._mesh,
[Replicate()],
stop_gradient=False,
)
def forward(self, x):
x.stop_gradient = False
out = self.relu_0(x) # triggle backward partial allreduce
out = self.linear_0(out)
out = self.relu_1(out)
out = self.linear_1(out)
out = self.relu_2(out) # triggle forward partial allreduce
return out
def create_data_loader():
images = np.random.rand(BATCH_NUM, IMAGE_SIZE).astype('float32')
labels = np.random.rand(BATCH_NUM, CLASS_NUM).astype('float32')
dataset = RandomDataset(images, labels, BATCH_NUM)
loader = DataLoader(dataset, batch_size=BATCH_SIZE)
return loader