Path already exists. Rename it to [/home/amax/PHD/Jiahao_Wang16/CT_MAR/image-restoration-sde-main/experiments/deraining/ir-sde_archived_240527-222942]
Traceback (most recent call last):
File "/home/amax/PHD/Jiahao_Wang16/CT_MAR/image-restoration-sde-main/codes/config/deraining/train.py", line 367, in
main()
File "/home/amax/PHD/Jiahao_Wang16/CT_MAR/image-restoration-sde-main/codes/config/deraining/train.py", line 106, in main
mkdir_and_rename(
File "/home/amax/PHD/Jiahao_Wang16/CT_MAR/image-restoration-sde-main/codes/utils/file_utils.py", line 62, in mkdir_and_rename
os.rename(path, new_name)
OSError: [Errno 39] Directory not empty: '/home/amax/PHD/Jiahao_Wang16/CT_MAR/image-restoration-sde-main/experiments/deraining/ir-sde' -> '/home/amax/PHD/Jiahao_Wang16/CT_MAR/image-restoration-sde-main/experiments/deraining/ir-sde_archived_240527-222942'
这是什么报错
Assistant
从报错信息中可以看到,代码试图将一个已经存在的目录重命名为另外一个名字,但目标目录已经存在并且不为空,因此产生了 OSError: [Errno 39] Directory not empty 错误。
在使用多GPU进行训练时,报错的原因通常与文件系统的并发访问和处理有关。具体来说,多GPU训练的一个通用方案是分布式数据并行(Distributed Data Parallel,DDP),它会在多个进程中并行运行代码。假设每个进程都在尝试创建或移动同一个目录,这是未同步的操作,可能导致多个进程之间的竞态条件(Race Condition)。
RuntimeError: Parent directory /home/amax/PHD/Jiahao_Wang16/CT_MAR/image-restoration-sde-main/experiments/deraining/ir-sde/models/dist does not exist.
[2024-05-28 10:21:53,209] torch.distributed.elastic.multiprocessing.api: [WARNING] Sending process 3932851 closing signal SIGTERM
[2024-05-28 10:21:53,210] torch.distributed.elastic.multiprocessing.api: [WARNING] Sending process 3932852 closing signal SIGTERM
[2024-05-28 10:21:53,211] torch.distributed.elastic.multiprocessing.api: [WARNING] Sending process 3932853 closing signal SIGTERM
/home/amax/anaconda3/lib/python3.11/multiprocessing/resource_tracker.py:224: UserWarning: resource_tracker: There appear to be 21 leaked semaphore objects to clean up at shutdown
warnings.warn('resource_tracker: There appear to be %d '
/home/amax/anaconda3/lib/python3.11/multiprocessing/resource_tracker.py:224: UserWarning: resource_tracker: There appear to be 21 leaked semaphore objects to clean up at shutdown
warnings.warn('resource_tracker: There appear to be %d '
/home/amax/anaconda3/lib/python3.11/multiprocessing/resource_tracker.py:224: UserWarning: resource_tracker: There appear to be 21 leaked semaphore objects to clean up at shutdown
warnings.warn('resource_tracker: There appear to be %d '
[2024-05-28 10:21:53,727] torch.distributed.elastic.multiprocessing.api: [ERROR] failed (exitcode: 1) local_rank: 0 (pid: 3932850) of binary: /home/amax/anaconda3/bin/python
Traceback (most recent call last):
File "", line 198, in _run_module_as_main
File "", line 88, in _run_code
File "/home/amax/anaconda3/lib/python3.11/site-packages/torch/distributed/launch.py", line 198, in
main()
File "/home/amax/anaconda3/lib/python3.11/site-packages/torch/distributed/launch.py", line 194, in main
launch(args)
File "/home/amax/anaconda3/lib/python3.11/site-packages/torch/distributed/launch.py", line 179, in launch
run(args)
File "/home/amax/anaconda3/lib/python3.11/site-packages/torch/distributed/run.py", line 803, in run
elastic_launch(
File "/home/amax/anaconda3/lib/python3.11/site-packages/torch/distributed/launcher/api.py", line 135, in call
return launch_agent(self._config, self._entrypoint, list(args))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/amax/anaconda3/lib/python3.11/site-packages/torch/distributed/launcher/api.py", line 268, in launch_agent
raise ChildFailedError(
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
import os
def ensure_dir_exists(path):
if not os.path.exists(path):
os.makedirs(path)
# 示例:确保目录存在
save_dir = "/home/amax/PHD/Jiahao_Wang16/CT_MAR/image-restoration-sde-main/experiments/deraining/ir-sde/models/dist"
ensure_dir_exists(save_dir)
修订后的样例代码
下面提供一个完整示例,确保数据加载器、模型、优化器、临时变量等都能够正确释放,并确保目录存在:
User
@torch.no_grad()
def make_grid(
tensor: Union[torch.Tensor, List[torch.Tensor]],
nrow: int = 8,
padding: int = 2,
normalize: bool = False,
value_range: Optional[Tuple[int, int]] = None,
scale_each: bool = False,
pad_value: float = 0.0,
) -> torch.Tensor:
"""
Make a grid of images.
def denormalize(tensor):
tensor = tensor.squeeze().float().cpu()
length = len(tensor)
result_mat = []
for j in range(length):
mat = tensor[j, ...].numpy()
result = 0 - sum(STAGE[1:-1])
for i in range(len(CLIP) - 1):
result += (mat[i]) * (STAGE[i + 1] - STAGE[i]) + STAGE[i]
result_mat.append(result)
top_row = np.hstack([result_mat[0], result_mat[1]])
bottom_row = np.hstack([result_mat[2], result_mat[3]])
final_matrix = np.vstack([top_row, bottom_row])
return final_matrix
该矩阵期望的输入维度和输出维度是多少
Assistant
要准确确定上述 denormalize 函数的输入和输出维度,我们需要仔细分析函数的各个操作步骤。
函数分析
初始准备:
python
tensor = tensor.squeeze().float().cpu()
tensor.squeeze() 会移除所有大小为1的维度。
.float() 将张量转换为浮点数类型。
.cpu() 将张量移到CPU上,确保后续的 .numpy() 操作能正常进行。
处理张量:
python
length = len(tensor)
result_mat = []
for j in range(length):
mat = tensor[j, ...].numpy()
result = 0 - sum(STAGE[1:-1])
for i in range(len(CLIP) - 1):
result += (mat[i]) * (STAGE[i + 1] - STAGE[i]) + STAGE[i]
result_mat.append(result)
Args:
tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)
or a list of images all of the same size.
nrow (int, optional): Number of images displayed in each row of the grid.
The final grid size is ``(B / nrow, nrow)``. Default: ``8``.
padding (int, optional): amount of padding. Default: ``2``.
normalize (bool, optional): If True, shift the image to the range (0, 1),
by the min and max values specified by ``value_range``. Default: ``False``.
value_range (tuple, optional): tuple (min, max) where min and max are numbers,
then these numbers are used to normalize the image. By default, min and max
are computed from the tensor.
scale_each (bool, optional): If ``True``, scale each image in the batch of
images separately rather than the (min, max) over all images. Default: ``False``.
pad_value (float, optional): Value for the padded pixels. Default: ``0``.
Returns:
grid (Tensor): the tensor containing grid of images.
"""
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
_log_api_usage_once(make_grid)
if not torch.is_tensor(tensor):
if isinstance(tensor, list):
for t in tensor:
if not torch.is_tensor(t):
raise TypeError(f"tensor or list of tensors expected, got a list containing {type(t)}")
else:
raise TypeError(f"tensor or list of tensors expected, got {type(tensor)}")
# if list of tensors, convert to a 4D mini-batch Tensor
if isinstance(tensor, list):
tensor = torch.stack(tensor, dim=0)
if tensor.dim() == 2: # single image H x W
tensor = tensor.unsqueeze(0)
if tensor.dim() == 3: # single image
if tensor.size(0) == 1: # if single-channel, convert to 3-channel
tensor = torch.cat((tensor, tensor, tensor), 0)
tensor = tensor.unsqueeze(0)
if tensor.dim() == 4 and tensor.size(1) == 1: # single-channel images
tensor = torch.cat((tensor, tensor, tensor), 1)
if normalize is True:
tensor = tensor.clone() # avoid modifying tensor in-place
if value_range is not None and not isinstance(value_range, tuple):
raise TypeError("value_range has to be a tuple (min, max) if specified. min and max are numbers")
def norm_ip(img, low, high):
img.clamp_(min=low, max=high)
img.sub_(low).div_(max(high - low, 1e-5))
def norm_range(t, value_range):
if value_range is not None:
norm_ip(t, value_range[0], value_range[1])
else:
norm_ip(t, float(t.min()), float(t.max()))
if scale_each is True:
for t in tensor: # loop over mini-batch dimension
norm_range(t, value_range)
else:
norm_range(tensor, value_range)
if not isinstance(tensor, torch.Tensor):
raise TypeError("tensor should be of type torch.Tensor")
if tensor.size(0) == 1:
return tensor.squeeze(0)
# make the mini-batch of images into a grid
nmaps = tensor.size(0)
xmaps = min(nrow, nmaps)
ymaps = int(math.ceil(float(nmaps) / xmaps))
height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding)
num_channels = tensor.size(1)
grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value)
k = 0
for y in range(ymaps):
for x in range(xmaps):
if k >= nmaps:
break
# Tensor.copy_() is a valid method but seems to be missing from the stubs
# https://pytorch.org/docs/stable/tensors.html#torch.Tensor.copy_
grid.narrow(1, y * height + padding, height - padding).narrow( # type: ignore[attr-defined]
2, x * width + padding, width - padding
).copy_(tensor[k])
k = k + 1
return grid
该函数的目的是什么, 如果输入是(4,3,128,128)的矩阵
import torch
import matplotlib.pyplot as plt
import math
# 假设我们有一个 (4, 3, 128, 128) 的输入张量
tensor = torch.rand(4, 3, 128, 128)
@torch.no_grad()
def make_grid(
tensor: Union[torch.Tensor, List[torch.Tensor]],
nrow: int = 8,
padding: int = 2,
normalize: bool = False,
value_range: Optional[Tuple[int, int]] = None,
scale_each: bool = False,
pad_value: float = 0.0,
) -> torch.Tensor:
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
_log_api_usage_once(make_grid)
if not torch.is_tensor(tensor):
if isinstance(tensor, list):
for t in tensor:
if not torch.is_tensor(t):
raise TypeError(f"tensor or list of tensors expected, got a list containing {type(t)}")
else:
raise TypeError(f"tensor or list of tensors expected, got {type(tensor)}")
if isinstance(tensor, list):
tensor = torch.stack(tensor, dim=0)
if tensor.dim() == 2:
tensor = tensor.unsqueeze(0)
if tensor.dim() == 3:
if tensor.size(0) == 1:
tensor = torch.cat((tensor, tensor, tensor), 0)
tensor = tensor.unsqueeze(0)
if tensor.dim() == 4 and tensor.size(1) == 1:
tensor = torch.cat((tensor, tensor, tensor), 1)
if normalize is True:
tensor = tensor.clone()
if value_range is not None and not isinstance(value_range, tuple):
raise TypeError("value_range has to be a tuple (min, max) if specified. min and max are numbers")
def norm_ip(img, low, high):
img.clamp_(min=low, max=high)
img.sub_(low).div_(max(high - low, 1e-5))
def norm_range(t, value_range):
if value_range is not None:
norm_ip(t, value_range[0], value_range[1])
else:
norm_ip(t, float(t.min()), float(t.max()))
if scale_each is True:
for t in tensor:
norm_range(t, value_range)
else:
norm_range(tensor, value_range)
if not isinstance(tensor, torch.Tensor):
raise TypeError("tensor should be of type torch.Tensor")
if tensor.size(0) == 1:
return tensor.squeeze(0)
nmaps = tensor.size(0)
xmaps = min(nrow, nmaps)
ymaps = int(math.ceil(float(nmaps) / xmaps))
height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding)
num_channels = tensor.size(1)
grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value)
k = 0
for y in range(ymaps):
for x in range(xmaps):
if k >= nmaps:
break
grid.narrow(1, y * height + padding, height - padding).narrow(
2, x * width + padding, width - padding
).copy_(tensor[k])
k = k + 1
return grid
# 使用make_grid函数
grid = make_grid(tensor, nrow=2)
# 绘制图像网格
def show(grid):
plt.imshow(grid.permute(1, 2, 0).cpu().numpy())
plt.axis('off')
plt.show()
show(grid)
import torch
import numpy as np
import math
import matplotlib.pyplot as plt
# 假设我们有一个 (4, 3, 128, 128) 的输入张量
tensor = torch.rand(4, 3, 128, 128)
# 定义 make_grid 函数(如前所示)
@torch.no_grad()
def make_grid(
tensor: Union[torch.Tensor, List[torch.Tensor]],
nrow: int = 8,
padding: int = 2,
normalize: bool = False,
value_range: Optional[Tuple[int, int]] = None,
scale_each: bool = False,
pad_value: float = 0.0,
) -> torch.Tensor:
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
_log_api_usage_once(make_grid)
if not torch.is_tensor(tensor):
if isinstance(tensor, list):
for t in tensor:
if not torch.is_tensor(t):
raise TypeError(f"tensor or list of tensors expected, got a list containing {type(t)}")
else:
raise TypeError(f"tensor or list of tensors expected, got {type(tensor)}")
if isinstance(tensor, list):
tensor = torch.stack(tensor, dim=0)
if tensor.dim() == 2:
tensor = tensor.unsqueeze(0)
if tensor.dim() == 3:
if tensor.size(0) == 1:
tensor = torch.cat((tensor, tensor, tensor), 0)
tensor = tensor.unsqueeze(0)
if tensor.dim() == 4 and tensor.size(1) == 1:
tensor = torch.cat((tensor, tensor, tensor), 1)
if normalize is True:
tensor = tensor.clone()
if value_range is not None and not isinstance(value_range, tuple):
raise TypeError("value_range has to be a tuple (min, max) if specified. min and max are numbers")
def norm_ip(img, low, high):
img.clamp_(min=low, max=high)
img.sub_(low).div_(max(high - low, 1e-5))
def norm_range(t, value_range):
if value_range is not None:
norm_ip(t, value_range[0], value_range[1])
else:
norm_ip(t, float(t.min()), float(t.max()))
if scale_each is True:
for t in tensor:
norm_range(t, value_range)
else:
norm_range(tensor, value_range)
if not isinstance(tensor, torch.Tensor):
raise TypeError("tensor should be of type torch.Tensor")
if tensor.size(0) == 1:
return tensor.squeeze(0)
nmaps = tensor.size(0)
xmaps = min(nrow, nmaps)
ymaps = int(math.ceil(float(nmaps) / xmaps))
height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding)
num_channels = tensor.size(1)
grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value)
k = 0
for y in range(ymaps):
for x in range(xmaps):
if k >= nmaps:
break
grid.narrow(1, y * height + padding, height - padding).narrow(
2, x * width + padding, width - padding
).copy_(tensor[k])
k = k + 1
return grid
# 生成网格
img_grid = make_grid(tensor, nrow=int(math.sqrt(len(tensor))), normalize=False).numpy()
# 转换通道顺序
img_np = np.transpose(img_grid[[2, 1, 0], :, :], (1, 2, 0))
# 绘制图像
def show(grid):
plt.imshow(grid)
plt.axis('off')
plt.show()
show(img_np)