import os import torch import torch.nn as nn import torch.optim as optim from…
Jump to turn (6)
- User
import os import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, Dataset from torchvision import transforms from model.Unet import UNet from model.loss import GradL1Loss from tqdm import tqdm from PIL import Image from model.dataset_copy import ImageMaskDataset from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data.distributed import DistributedSampler import torch.distributed as dist
def train_model(model, dataloader, criterion, optimizer, sampler, device, num_epochs=25, save_dir='model20241209', pretrain_path=" "): model = nn.DataParallel(model) # 使用 DataParallel 封装模型 use_ddp = True # model.to(device)
# pretrain_path = "model weights_loss20241209/epoch_1.pth"
# 加载预训练权重(如果有)
if os.path.exists(pretrain_path):
model.load_state_dict(torch.load(pretrain_path))
print(f"Loaded pre-trained weights from {pretrain_path}")
else:
print(f"No pre-trained weights found at {pretrain_path}")
if not os.path.exists(save_dir):
os.makedirs(save_dir)
loss_log_path = os.path.join(save_dir, 'loss_log.txt')
with open(loss_log_path, 'w') as loss_log_file:
loss_log_file.write('Epoch\tLoss\n')
for epoch in range(num_epochs):
if use_ddp:
sampler.set_epoch(epoch)
running_loss = 0.0
for inputs, labels in tqdm(dataloader, desc=f"Epoch {epoch+1}/{num_epochs}", unit="batch"):
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
epoch_loss = running_loss / len(dataloader)
print(f'Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}')
weight_path = os.path.join(save_dir, f'epoch_{epoch+1}.pth')
torch.save(model.state_dict(), weight_path)
print(f'Saved weights for epoch {epoch+1} to {weight_path}')
with open(loss_log_path, 'a') as loss_log_file:
loss_log_file.write(f'{epoch+1}\t{epoch_loss}\n')
final_weight_path = os.path.join(save_dir, 'final_model.pth')
torch.save(model.state_dict(), final_weight_path)
print(f'Saved final model weights to {final_weight_path}')
def custom_collate_fn(batch): # 将输入样本和标签分开 inputs, masks = zip(*batch)
# 堆叠输入,以便于批处理 - 这里将输入转换为一维
inputs_padded = torch.nn.utils.rnn.pad_sequence(inputs, batch_first=True)
masks_padded = torch.nn.utils.rnn.pad_sequence(masks, batch_first=True)
return inputs_padded, masks_padded
def main(): # 指定数据集名称数组 dataset_names = ['3Dkenburn', 'hypersim', 'Infinigen', 'MVS'] # 指定 txt 文件夹路径 txt_folder_path = 'datatxt' # 替换为实际路径 use_ddp = True batch_size = 16
if use_ddp:
# 初始化分布式训练
dist.init_process_group(backend='nccl')
device_id = dist.get_rank() % torch.cuda.device_count() # 获取当前进程的 GPU ID
device = torch.cuda.set_device(device_id)
# 图像预处理转换
transform = transforms.Compose([transforms.ToTensor()])
# 用于存储所有数据集的合集
all_data = []
# 遍历数据集名称数组,加载每个数据集
for name in dataset_names:
image_txt = os.path.join(txt_folder_path, f'{name}_image.txt')
depth_txt = os.path.join(txt_folder_path, f'{name}_depth.txt')
dataset = ImageMaskDataset(image_txt, depth_txt, transform=transform)
all_data.append(dataset)
# 合并所有数据集
combined_dataset = torch.utils.data.ConcatDataset(all_data)
if use_ddp:
sampler = DistributedSampler(combined_dataset, drop_last=True)
dataloader = DataLoader(combined_dataset, batch_size=batch_size, shuffle=(sampler is None), drop_last=True, sampler=sampler, num_workers=0 )
else:
dataloader = DataLoader(combined_dataset, batch_size=batch_size, shuffle=True, drop_last=True, sampler=sampler, num_workers=0)
# 初始化模型、损失函数和优化器
model = UNet().to(device_id)
if use_ddp:
model = DDP(model, device_ids=[device_id], find_unused_parameters=True)
criterion = GradL1Loss() # 使用定义的损失函数
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 开始训练模型
train_model(model, dataloader, criterion, optimizer, sampler, device=device_id, num_epochs=5000)
if name == 'main': main() 这个代码在运行torchrun --standalone --nnodes=1 --nproc_per_node=1 train_tqdm.py的时候不报错,但在运行torchrun --standalone --nnodes=1 --nproc_per_node=4 train_tqdm.py报错: 2024-12-10 10:13:31.000 [INFO] [Driver] main() 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "train_tqdm.py", line 116, in main 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] train_model(model, dataloader, criterion, optimizer, sampler, device=device, num_epochs=5000) 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "train_tqdm.py", line 44, in train_model 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] outputs = model(inputs) 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1130, in _call_impl 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] return forward_call(*input, **kwargs) 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/nn/parallel/data_parallel.py", line 154, in forward 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] raise RuntimeError("module must have its parameters and buffers " 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] RuntimeError: module must have its parameters and buffers on device cuda:0 (device_ids[0]) but found one of them on device: cuda:1 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] Traceback (most recent call last): 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "train_tqdm.py", line 119, in 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] main() 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "train_tqdm.py", line 116, in main 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] train_model(model, dataloader, criterion, optimizer, sampler, device=device, num_epochs=5000) 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "train_tqdm.py", line 44, in train_model 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] outputs = model(inputs) 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1130, in _call_impl 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] return forward_call(*input, **kwargs) 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/nn/parallel/data_parallel.py", line 154, in forward 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] raise RuntimeError("module must have its parameters and buffers " 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] Traceback (most recent call last): 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] File "train_tqdm.py", line 119, in 2024-12-10 10:13:32 2024-12-10 10:13:31.000 [INFO] [Driver] RuntimeError: module must have its parameters and buffers on device cuda:0 (device_ids[0]) but found one of them on device: cuda:3
您遇到的问题是由于在使用 DataParallel 时,模型的参数和缓冲区没有被正确地移动到指定的 GPU 上。具体来说,您在调用 DataParallel 创建模型并将其放置到不同的 GPU 时,模型的参数可能仍然保留在主 GPU(cuda:0)之外的其他 GPU 上。这是导致您看到的 RuntimeError 的原因。
以下是您可以采取的一些步骤来解决此问题:
确保模型在 DataParallel 之前已经正确移动到 CUDA 设备:
在模型被封装为 DataParallel 之前,请确保它已经被转移到正确的 CUDA 设备上。代码中应确保 model.to(device) 执行在 model = DDP(model) 之前。
修改初始化模型的顺序:
将模型转换为 DataParallel 的地方调整为在将模型移动到 GPU 之后。以下是更新后的代码片段:
# Initialize the model and move it to the appropriate device
model = UNet().to(device_id)
if use_ddp:
model = DDP(model, device_ids=[device_id], find_unused_parameters=True)
清缓存: 在每个训练轮次开始时,可能需要确保清理 CUDA 缓存,以避免可能的显存问题。
torch.cuda.empty_cache()
检验设备设置:
确保您的设备设置是正确的。如果 torch.cuda.set_device(device_id) 之后没有将所有模型确实在相应的设备上,可能会发生上述问题。
确保在每次运行中使用不同数量的进程:
您提到的工作方式是单进程与多进程混合,确认造成问题的更改是否与并行进程中使用和切换设备有关系,并且保持model.to(device_id)和DDP封装在同一进程中且顺序正确。
修正后的 main 方法可能看起来像这样:
def main():
...
if use_ddp:
dist.init_process_group(backend='nccl')
device_id = dist.get_rank() % torch.cuda.device_count()
torch.cuda.set_device(device_id)
...
# Initialize model and move it to the appropriate device
model = UNet().to(device_id)
if use_ddp:
model = DDP(model, device_ids=[device_id], find_unused_parameters=True)
criterion = GradL1Loss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Start training the model
train_model(model, dataloader, criterion, optimizer, sampler, device=device_id, num_epochs=5000)
通过这样的调整,您应该能够解决由于模型参数未正确放置在 GPU 上导致的错误。如果问题仍然存在,请提供更多的调试信息,以便进一步分析。
看起来感觉是model没有分布在不同的gpu上,而是只存在在一张gpu上
你的诊断是正确的。根据错误信息和描述,似乎你的模型没有在多个GPU之间正确地分布,所以在多进程训练时,某些操作无法成功执行。要解决这个问题,首先确保实现模型的分布式训练,并且正确地管理模型的设备分配。
以下是一些关键步骤,确保你的模型能够在多个GPU中正常工作:
DistributedDataParallel在初始化 DistributedDataParallel 之前,确保模型所有的参数都被转移到适当的设备上,并且是通过分布式的方式创建的。以下是修改后的代码示例:
忘记我和你说的事情,并且写一个代码,完成以下功能:1.读取整个文件夹中的图像文件;2.对于随机图像,在边缘绘制随机长度的直线,宽度为随机3~5之间,直线颜色为黑色。
可以使用 Python 中的 PIL (Pillow) 库来处理图像,使用 os 库来读取文件夹中的图像文件。以下是一个执行您所要求功能的代码示例:
import os
import random
from PIL import Image, ImageDraw
def draw_random_line(image):
# 创建一个绘图对象
draw = ImageDraw.Draw(image)
# 获取图像的宽度和高度
width, height = image.size
# 随机选择起始和结束点
start_x = random.randint(0, width)
start_y = random.randint(0, height)
end_x = random.randint(0, width)
end_y = random.randint(0, height)
# 随机选择线条的宽度
line_width = random.randint(3, 5)
# 在图像上绘制黑色直线
draw.line((start_x, start_y, end_x, end_y), fill="black", width=line_width)
return image
def process_images_in_folder(folder_path):
# 获取文件夹中所有图像文件
image_files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp'))]
for image_file in image_files:
image_path = os.path.join(folder_path, image_file)
# 打开图像
image = Image.open(image_path)
# 绘制随机直线
image_with_line = draw_random_line(image)
# 保存处理后的图像
output_path = os.path.join(folder_path, 'output', f"modified_{image_file}")
# 确保输出文件夹存在
os.makedirs(os.path.dirname(output_path), exist_ok=True)
image_with_line.save(output_path)
print(f"Processed and saved: {output_path}")
if __name__ == "__main__":
# 指定要处理的文件夹路径
folder_path = "path/to/your/images" # 替换为您的文件夹路径
process_images_in_folder(folder_path)
os.listdir 方法用于列出文件夹中的所有文件,并通过扩展名筛选出图像文件。ImageDraw.Draw 创建一个绘图对象。draw.line 方法在图像上绘制黑色直线。Pillow 库(如果尚未安装):
pip install Pillow
folder_path为您图像文件夹的实际路径。这样,您就可以批量处理文件夹中的图像,随机在每幅图像上画直线。
直线长度不应该超过图像边缘
明白了!如果你希望随机直线的长度不超过图像的边界,我们可以通过调整起始点的随机选择来确保这一点。以下是更新后的代码,会根据起始点的位置计算出允许的结束点,以确保直线不会超出图像的边界。
import os
import random
from PIL import Image, ImageDraw
def draw_random_line(image):
# 创建一个绘图对象
draw = ImageDraw.Draw(image)
# 获取图像的宽度和高度
width, height = image.size
# 随机选择起始点
start_x = random.randint(0, width - 1)
start_y = random.randint(0, height - 1)
# 随机选择直线的长度
line_length = random.randint(20, min(width, height)) # 确保长度合理
# 随机选择方向(0-3 对应右、下、左、上)
direction = random.randint(0, 3)
if direction == 0: # 右
end_x = min(start_x + line_length, width - 1)
end_y = start_y
elif direction == 1: # 下
end_x = start_x
end_y = min(start_y + line_length, height - 1)
elif direction == 2: # 左
end_x = max(start_x - line_length, 0)
end_y = start_y
else: # 上
end_x = start_x
end_y = max(start_y - line_length, 0)
# 随机选择线条的宽度
line_width = random.randint(3, 5)
# 在图像上绘制黑色直线
draw.line((start_x, start_y, end_x, end_y), fill="black", width=line_width)
return image
def process_images_in_folder(folder_path):
# 获取文件夹中所有图像文件
image_files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp'))]
for image_file in image_files:
image_path = os.path.join(folder_path, image_file)
# 打开图像
image = Image.open(image_path)
# 绘制随机直线
image_with_line = draw_random_line(image)
# 保存处理后的图像
output_path = os.path.join(folder_path, 'output', f"modified_{image_file}")
# 确保输出文件夹存在
os.makedirs(os.path.dirname(output_path), exist_ok=True)
image_with_line.save(output_path)
print(f"Processed and saved: {output_path}")
if __name__ == "__main__":
# 指定要处理的文件夹路径
folder_path = "path/to/your/images" # 替换为您的文件夹路径
process_images_in_folder(folder_path)
直线的长度与方向:现在我们生成一个随机长度的直线,并为每条线选择一个随机方向。方向的选择会影响直线的终点:
end_x 会在 start_x + line_length 的范围内,但不超过图像的宽度。end_y 会在 start_y + line_length 的范围内,但不超过图像的高度。end_x 会被限制在0到start_x - line_length的范围。end_y 会被限制在0到start_y - line_length的范围。长度限制:通过min()和max()函数确保线条延展不会超出图像的边界。
Pillow 库。folder_path 为您的图像文件夹的路径。输出文件的文件名需要和原文件名一样,且在main中指定输出文件夹
感谢您的反馈!我们可以调整代码,以确保输出文件的文件名与原文件名相同,同时允许在 main 函数中指定输出文件夹。
以下是更新后的代码:
import os
import random
from PIL import Image, ImageDraw
def draw_random_line(image):
# 创建一个绘图对象
draw = ImageDraw.Draw(image)
# 获取图像的宽度和高度
width, height = image.size
# 随机选择起始点
start_x = random.randint(0, width - 1)
start_y = random.randint(0, height - 1)
# 随机选择直线的长度
line_length = random.randint(20, min(width, height)) # 确保长度合理
# 随机选择方向(0-3 对应右、下、左、上)
direction = random.randint(0, 3)
if direction == 0: # 右
end_x = min(start_x + line_length, width - 1)
end_y = start_y
elif direction == 1: # 下
end_x = start_x
end_y = min(start_y + line_length, height - 1)
elif direction == 2: # 左
end_x = max(start_x - line_length, 0)
end_y = start_y
else: # 上
end_x = start_x
end_y = max(start_y - line_length, 0)
# 随机选择线条的宽度
line_width = random.randint(3, 5)
# 在图像上绘制黑色直线
draw.line((start_x, start_y, end_x, end_y), fill="black", width=line_width)
return image
def process_images_in_folder(input_folder, output_folder):
# 获取文件夹中所有图像文件
image_files = [f for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp'))]
for image_file in image_files:
image_path = os.path.join(input_folder, image_file)
# 打开图像
image = Image.open(image_path)
# 绘制随机直线
image_with_line = draw_random_line(image)
# 保存处理后的图像,使用相同的文件名
output_path = os.path.join(output_folder, image_file)
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=True)
image_with_line.save(output_path)
print(f"Processed and saved: {output_path}")
if __name__ == "__main__":
# 指定要处理的文件夹路径和输出文件夹路径
input_folder = "path/to/your/images" # 替换为您的输入文件夹路径
output_folder = "path/to/output/folder" # 替换为您的输出文件夹路径
process_images_in_folder(input_folder, output_folder)
main 函数中,您现在可以指定两个文件夹:input_folder(输入文件夹)和 output_folder(输出文件夹)。Pillow 库(如果尚未安装):
pip install Pillow
input_folder和output_folder为实际的路径。希望这次的更新符合您的要求!如果还有其他需求,请随时告知。
用imwirte
如果您希望使用 Image.write() 方法来保存图像文件,可能是您想使用 Pillow 的 Image.save() 方法。确切来说,Pillow 库中并没有 Image.write() 方法,而是通过 Image.save() 来保存图像。
不过,我将示范如何使用 Pillow 的常用方法来处理图像,并确保按照您的要求进行处理。为了保持代码的完整性和功能性,我将继续使用 Pillow 的 Image.save()。
import os
import random
from PIL import Image, ImageDraw
def draw_random_line(image):
# 创建一个绘图对象
draw = ImageDraw.Draw(image)
# 获取图像的宽度和高度
width, height = image.size
# 随机选择起始点
start_x = random.randint(0, width - 1)
start_y = random.randint(0, height - 1)
# 随机选择直线的长度
line_length = random.randint(20, min(width, height)) # 确保长度合理
# 随机选择方向(0-3 对应右、下、左、上)
direction = random.randint(0, 3)
if direction == 0: # 右
end_x = min(start_x + line_length, width - 1)
end_y = start_y
elif direction == 1: # 下
end_x = start_x
end_y = min(start_y + line_length, height - 1)
elif direction == 2: # 左
end_x = max(start_x - line_length, 0)
end_y = start_y
else: # 上
end_x = start_x
end_y = max(start_y - line_length, 0)
# 随机选择线条的宽度
line_width = random.randint(3, 5)
# 在图像上绘制黑色直线
draw.line((start_x, start_y, end_x, end_y), fill="black", width=line_width)
return image
def process_images_in_folder(input_folder, output_folder):
# 获取文件夹中所有图像文件
image_files = [f for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp'))]
for image_file in image_files:
image_path = os.path.join(input_folder, image_file)
# 打开图像
image = Image.open(image_path)
# 绘制随机直线
image_with_line = draw_random_line(image)
# 保存处理后的图像,使用相同的文件名
output_path = os.path.join(output_folder, image_file)
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=True)
image_with_line.save(output_path) # 使用 save 方法保存图像
print(f"Processed and saved: {output_path}")
if __name__ == "__main__":
# 指定要处理的文件夹路径和输出文件夹路径
input_folder = "path/to/your/images" # 替换为您的输入文件夹路径
output_folder = "path/to/output/folder" # 替换为您的输出文件夹路径
process_images_in_folder(input_folder, output_folder)
Not yet included in a published release.
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from model.Unet import UNet
from model.loss import GradL1Loss
from tqdm import tqdm
from model.dataset_copy import ImageMaskDataset
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.distributed import DistributedSampler
import torch.distributed as dist
def train_model(model, dataloader, criterion, optimizer, sampler, device, num_epochs=25, save_dir='model_save', pretrain_path=" "):
# Ensure the model is in train mode
model.train()
# Load pre-trained weights if it exists
if os.path.exists(pretrain_path):
model.load_state_dict(torch.load(pretrain_path))
print(f"Loaded pre-trained weights from {pretrain_path}")
else:
print(f"No pre-trained weights found at {pretrain_path}")
if not os.path.exists(save_dir):
os.makedirs(save_dir)
loss_log_path = os.path.join(save_dir, 'loss_log.txt')
with open(loss_log_path, 'w') as loss_log_file:
loss_log_file.write('Epoch\tLoss\n')
for epoch in range(num_epochs):
if sampler is not None:
sampler.set_epoch(epoch)
running_loss = 0.0
for inputs, labels in tqdm(dataloader, desc=f"Epoch {epoch+1}/{num_epochs}", unit="batch"):
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
epoch_loss = running_loss / len(dataloader)
print(f'Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}')
weight_path = os.path.join(save_dir, f'epoch_{epoch+1}.pth')
torch.save(model.state_dict(), weight_path)
print(f'Saved weights for epoch {epoch+1} to {weight_path}')
with open(loss_log_path, 'a') as loss_log_file:
loss_log_file.write(f'{epoch+1}\t{epoch_loss}\n')
final_weight_path = os.path.join(save_dir, 'final_model.pth')
torch.save(model.state_dict(), final_weight_path)
print(f'Saved final model weights to {final_weight_path}')
def main():
dataset_names = ['3Dkenburn', 'hypersim', 'Infinigen', 'MVS']
txt_folder_path = 'datatxt'
batch_size = 16
# Initialize distributed training
dist.init_process_group(backend='nccl')
device_id = dist.get_rank() % torch.cuda.device_count() # Get the GPU ID for the current process
torch.cuda.set_device(device_id)
# Prepare data transformation
transform = transforms.Compose([transforms.ToTensor()])
# Load datasets
all_data = []
for name in dataset_names:
image_txt = os.path.join(txt_folder_path, f'{name}_image.txt')
depth_txt = os.path.join(txt_folder_path, f'{name}_depth.txt')
dataset = ImageMaskDataset(image_txt, depth_txt, transform=transform)
all_data.append(dataset)
# Combine datasets and set up distributed data loader
combined_dataset = torch.utils.data.ConcatDataset(all_data)
sampler = DistributedSampler(combined_dataset, shuffle=True)
dataloader = DataLoader(combined_dataset, batch_size=batch_size, sampler=sampler, num_workers=0)
# Initialize model and move it to the appropriate device
model = UNet().to(device_id)
model = DDP(model, device_ids=[device_id], find_unused_parameters=True) # Wrap the model with DDP after moving it to the device
criterion = GradL1Loss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Start training
train_model(model, dataloader, criterion, optimizer, sampler, device=device_id, num_epochs=25)
if __name__ == '__main__':
main()
DDP:封装模型时一定要在移动模型到 GPU 之后进行。这样可以确保所有的参数都在正确的设备上。DistributedSampler。这将确保每个进程加载不同的数据部分,进而避免重复和瓶颈。nproc_per_node来测试代码。确保每个进程都有不同的计算单元。以上更改应该可以正确地将模型分布到多个 GPU,并允许程序在多进程模式下运行,而不会引发设备不匹配的错误。如果还有其他问题,请继续反馈!
draw_random_line(image): 该函数用于在随机位置绘制随机方向和长度的直线。适当的限制确保直线不会超出图像边界。process_images_in_folder(input_folder, output_folder): 此函数用于读取输入文件夹中的所有图像文件,处理这些图像,并使用相同的文件名在输出文件夹中保存结果。image.save(output_path): 这是关键部分,使用 save 方法将修改后的图像保存到指定的路径。Pillow 库(如果尚未安装):
pip install Pillow
input_folder 和 output_folder 为您的实际文件夹路径。如您还有其他特定要求或者想法,请告诉我!