python 24

[warning] Leaking Caffe2 thread-pool after fork 해결하기

Leaking Caffe2 thread-pool after fork 해결하기 + pin_memory에 대해 알아보자 한번씩 아래와 같은 경고들이 터미널을 점령해서 진행 상황을 보는데 방해가 될 때가 있다. 구글링 결과, 이미 많은 사람들이 토론을 벌이고 있었고.. (참고한 사이트: https://github.com/pytorch/pytorch/issues/57273) 내가 해결한 방법은 DataLoader의 argument 중, pin_memory를 False로 변경하는 것이다. pin_memory = False로 변경해주니 경고 메세지들이 사라졌다. 그런데 이걸 마음대로 False로 바꿔도 되는거야? DataLoader에서 pin_memory Dataset 샘플들을 CPU에 load하고, 훈련 중에 G..

python 2022.05.27

[python] Logger class, timezone Seoul

Logger Class 모델을 돌리며 터미널의 출력들을 txt 또는 log 파일로 저장하고 싶으면서, 동시에 터미널에서도 실시간으로 확인하고 싶을 때 Logger class를 사용하면 된다. 내가 사용하는 Logger 코드는 다음과 같다. class Logger(object): def __init__(self): td = datetime.datetime.now(timezone('Asia/Seoul')) file_name = td.strftime('%m-%d_%H.%M') + ".log" self.terminal = sys.stdout self.log = open(file_name, "a") def write(self, temp): self.terminal.write(temp) self.log.write(..

python 2022.05.27

[에러] RuntimeError: CUDA error: device-side assert triggered

오늘도 평화로운 pytorch 에러 일기 에러 내용: loss = self.loss(output, target) File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl return forward_call(*input, **kwargs) File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/loss.py", line 1122, in forward return F.cross_entropy(input, target, weight=self.weight, File "/opt/conda/lib/python3.8/site-packages/t..

python 2022.05.20

[python] os.mkdirs 에러

os.makedirs로 원하는 경로의 폴더를 만들고 싶은데, 해당 디렉터리가 이미 존재하는 경우에 FileExistsError가 뜬다. 해결 방법 os.makedirs(path)에 exist_ok 파라미터를 추가한다. #before os.makedirs(path) #after os.makedirs(path, exist_ok = True)​ exist_ok = True를 추가하면, 디렉터리가 이미 존재했다면 에러가 생기지 않은 채 넘어가고, 존재하지 않았다면 만든다. exist_ok = False의 경우는 디렉터리가 존재했다면 처음과 같은 에러가 뜨게 된다. 끗

python 2022.03.31

[python] numpy array, torch tensor 크기 확인하기

가끔 헷갈릴 때가 있어서 크기 확인 방법을 한 번에 정리해보자! 1. numpy array 함수들: shape, size shape: 행렬의 각 차원 크기를 반환한다. size: 행렬의 전체 사이즈, 즉 원소 개수를 반환한다. np.shape는 아래와 같이 torch.tensor에 대해서도 사용할 수 있다. np.shape(tensor) 역시 각 차원의 길이를 반환한다. 2. Torch tensor tensor.shape == np.shape(tensor): 각 차원의 길이, 즉 shape 반환 a.size(0) == a.shape[0]: 차원 0의 길이 반환 a.size(1) == a.shape[1]: 차원 1의 길이 반환

python 2022.03.22

[torch] model parameter 개수/값 확인

모델 파라미터 개수 확인 python에서 모델의 파라미터 개수를 세기 위해서 다음 함수를 추가하면 된다. print(count_parameters(model)) #사용 def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) 코드 해석 model.parameters()의 파라미터 텐서들에 대해서 requires_grad = True라면 해당 파라미터 텐서의 numel값들을 더한다. torch.numel(input) input: 입력 tensor. 텐서의 모든 원소의 수를 반환한다. requires_grad Tensor의 옵션. True로 되어있어야 해당 tensor의 gradient를 구..

python 2022.03.16

[python] Iterator slicing

Iterator class의 객체를 슬라이싱 하는 방법을 알아보자! Iterator를 사용함으로서 모든 요소를 저장할 필요가 없어 CPU 메모리를 절약할 수 있고, 코드를 깔끔하게 만들 수 있다. 자세한 설명은 위 사진 source 링크 참조 딥러닝 사용 예: Autoencoder에서 encoder부분만 필요해서, 학습된 모델에서 encoder부분 parameter만 뽑아내고 싶다. 이 때 파라미터들은 loaded_model.parameters() 에 저장되어 있는데, parameters()는 iterator 형식이다. 즉, for문을 통해 각 객체에 접근할 수 있는 type이다. 따라서 encoder 부분만 slicing하기 위해서는, 먼저 itertools 모듈을 import해야 한다. import ..

python 2021.12.24