본문 바로가기

블루아카이브

에러 기록

 

ImportError: libGL.so.1: cannot open shared object file: No such file or directory 해결법

RUN apt-get update
RUN apt-get install ffmpeg libsm6 libxext6  -y

W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. 

같은 에러가 떠서 만약 안된다면 chmod 777 /tmp 실시

 

$ git add .
$ git commit -m "Description of changes"
$ git push

 


CONDA 환경 변경

export PATH=/home/mmlab/anaconda3/envs/muren/bin:$PATH

 

CUDA_VISIBLE_DIVICES=1  : GPU 중 어떤 것을 사용할지 선택

 

for name, param in model.net_g.named_parameters():
    print(f"Layer: {name} | Size: {param.size()} | Number of Parameters: {param.numel()}")


RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one.
This error indicates that your module has parameters that were not used in producing loss.
You can enable unused parameter detection by
(1) passing the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`; (2) making sure all `forward` function outputs participate in calculating loss.
If you already have done the above two steps, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's `forward` function.
Please include the loss function and the structure of the return value of `forward` of your module when reporting this issue (e.g. list, dict, iterable). Killing subprocess 4019

The error you're seeing is related to the use of `DistributedDataParallel` (DDP) in PyTorch. DDP wraps around your model and parallelizes the forward and backward passes across multiple GPUs. The error message suggests that there are some parameters in your model that were not used in producing the loss.

Here's a breakdown of the error and potential solutions:

1. **Unused Parameters**: If your model has parameters that aren't used in every forward pass, DDP can throw this error. This is because DDP expects all model parameters to receive gradients, but if a parameter isn't used, it won't receive any gradients, leading to this error.

2. **Solutions**:
   - **Enable Detection of Unused Parameters**: As the error message suggests, you can pass `find_unused_parameters=True` to `DistributedDataParallel` when wrapping your model. This will allow DDP to handle models with unused parameters.
     ```python
     model = torch.nn.parallel.DistributedDataParallel(model, find_unused_parameters=True)
     ```
   - **Ensure All Outputs are Used**: Make sure that all outputs from the `forward` function of your model are used in calculating the loss. If you have multiple outputs and you're only using some of them for the loss, this can cause the error.
   - **Check Model Forward Return Structure**: If you're returning a complex structure (like a dictionary or a list) from the `forward` method of your model, ensure that DDP can correctly identify all output tensors. Simplifying the return structure can help.

3. **Debugging**:
   - **Print Model Parameters**: Before the forward pass, print out all model parameters and check if any of them seem unnecessary or if you've accidentally duplicated layers.
   - **Gradually Build Up Model**: If you're still having trouble identifying the issue, start with a simpler version of your model and gradually add components, checking at each stage if the error appears.

4. **Other Considerations**:
   - If you're using features like model checkpointing, ensure that the model's state is being loaded correctly and that no extra parameters are being introduced.
   - If you've recently modified the architecture of your model, ensure that old parameters aren't lingering.

Remember, the key is to ensure that every parameter in your model is involved in the computation of the loss in every forward pass when using DDP.

 

이 때, 사용하지 않는 파라미터를 식별하는 방법 & find_unsed_parameters=True의 효과 :

Great to hear that adding `find_unused_parameters=True` resolved the issue. Let's dive into what this does and how you can identify unused parameters.

1. **What is `find_unused_parameters`?**
   - `DistributedDataParallel` (DDP) wraps around your model and parallelizes the forward and backward passes across multiple GPUs. By default, DDP expects that every parameter of the model participates in computing the loss. If any parameter does not receive a gradient (because it wasn't used in the forward pass), DDP will throw an error.
   - `find_unused_parameters=True` tells DDP to be more lenient. It will search for parameters that did not receive a gradient and handle them gracefully by not expecting a gradient for them. This is useful for models that, for some reason, might not use all their parameters in every forward pass.

2. **How to Identify Unused Parameters**:
   - While `find_unused_parameters=True` allows training to proceed without errors, it's often a good idea to identify and address the root cause, especially if the unused parameters are unintentional.
   - Here's a way to identify unused parameters:

     ```python
     # After a forward and backward pass
     for name, param in model.named_parameters():
         if param.grad is None:
             print(f"Parameter {name} did not receive a gradient.")
     ```

     This code iterates over all parameters of the model and prints out the names of parameters that did not receive a gradient. If a parameter's gradient is `None`, it means that parameter was not used in the forward pass.

3. **Why Address Unused Parameters?**
   - **Efficiency**: Unused parameters consume memory and computational resources without contributing to the model's performance.
   - **Potential Bugs**: Sometimes, unused parameters can indicate a bug in the model's architecture or the data processing pipeline.
   - **Model Interpretability**: A leaner model with only necessary parameters is easier to understand and debug.

In summary, while `find_unused_parameters=True` provides a quick fix to the error, it's a good practice to investigate why certain parameters are unused, especially if it's unexpected.


파이썬 버전 변경

우분투에서 파이썬 버전 변경하기 · Seongkyun Han's blog

 

우분투에서 파이썬 버전 변경하기 · Seongkyun Han's blog

또한 alternative는 python뿐만이 아니라 java와 같은 다양한 프로그램의 버전을 관리하는데 사용이 가능하다.

seongkyun.github.io


docker을 생성할 때, 쿠다 버전을 확인하거나

혹은 이미지를 보고 싶으면

docker hub를 들어가서 검색하면 된다.

가령 cuda 10.1버전이 필요하다면 거기에서 tag에 10.1-cudnn8-devel을 검색하자.

devel은 develop 약자임


# Check if CUDA is available
if torch.cuda.is_available():   
print("CUDA is available!")   
device = torch.device("cuda")   

# Create tensors on GPU   
x = torch.randn(3, 3).to(device)   
y = torch.randn(3, 3).to(device)   

# Perform a basic operation   
z = x + y    print("Result tensor:\n", z)   

# Check GPU details   
print("\nGPU Details:")   
print("Name:", torch.cuda.get_device_name(0))   
print("Current Memory Allocated:", torch.cuda.memory_allocated(0) / 1e6, "MB")   
print("Max Memory Allocated:", torch.cuda.max_memory_allocated(0) / 1e6, "MB")   

Feature extraction 모듈

register_hook

torch model extraction


[W accumulate_grad.h:185] Warning: grad and param do not obey the gradient layout contract. This is not an error, but may impair performance.
grad.sizes() = [64, 64, 1, 1], strides() = [64, 1, 1, 1]
param.sizes() = [64, 64, 1, 1], strides() = [64, 1, 64, 64] (function operator())

해당 에러 발생.

지금 보이는 경고 메시지는 PyTorch를 사용하여 신경망을 훈련할 때 메모리에 있는 그래디언트와 파라미터의 레이아웃과 관련이 있다. 오류는 아니지만 그래디언트와 파라미터가 메모리에 저장되고 액세스되는 방식에 잠재적인 비효율성을 나타내므로 훈련 과정의 성능에 영향을 미칠 수 있다.

메시지를 요약하면 다음과 같습니다:

1. **Context**: 경고는 각 매개변수에 대해 계산된 그래디언트가 여러 백워드 패스에 걸쳐 합산되는 역전파 알고리즘의 단계인 그래디언트 누적 중에 생성된다(미니 배치에 걸친 그래디언트 누적과 같은 시나리오에서 유용함).

2. **구배 및 파라미터 레이아웃**:
- 메모리에 있는 텐서의 배치는 그 크기(모양)와 보폭에 의해 결정된다. 텐서의 크기는 각 차원에 얼마나 많은 원소가 있는지 알려준다. 텐서의 보폭은 각 차원의 다음 원소로 가기 위해 저장소에 있는 원소의 수를 알려준다.
- 당신의 경우:
- 그래디언트('grad')는 크기가 [64, 64, 1, 1]이고 진각이 [64, 1, 1, 1]이다.
- 파라미터('param')의 크기는 [64, 64, 1, 1]이고 진일보는 [64, 1, 64, 64]이다.

3. **진법 불일치**:
- 경고는 그래디언트 텐서와 파라미터 텐서의 보폭이 일치하지 않는다는 것을 지적하고 있다. 이러한 불일치는 그래디언트와 파라미터에 대한 메모리 내의 데이터 레이아웃이 상이하다는 것을 의미한다.
- 이상적으로, 효율적인 계산을 위해, 그래디언트들의 레이아웃(스트라이드들)이 대응하는 파라미터들의 레이아웃과 일치하기를 원한다. 레이아웃들이 일치하면, 엘리먼트들이 메모리에서 순차적으로 레이아웃되기 때문에 그래디언트 축적과 같은 연산들이 더 효율적으로 수행될 수 있다.

4. **성과에 미치는 영향**:
- 경고는 이러한 불일치가 "성능을 손상시킬 수 있다"는 것을 나타낸다. 왜냐하면, 보폭이 일치하지 않을 때, 시스템은 연산들을 수행하기 전에 메모리 내의 데이터를 정렬하기 위한 추가 작업을 수행할 필요가 있고, 이는 연산들을 느리게 할 수 있기 때문이다.
- 그러나 이것은 단지 잠재적인 성능 문제일 뿐이다. 훈련 속도에 미치는 실제 영향은 모델의 세부 사항, 데이터의 크기, 사용하는 하드웨어에 따라 다를 수 있다.

5. **경고 주소 지정**: - 많은 경우 모델이 올바르게 교육을 받고 있고 성능이 양호한 경우 이 경고를 안전하게 무시할 수 있습니다.
- 성능을 최적화하려고 한다면 모델에서 그래디언트와 매개변수가 일치하는 보폭을 확보하기 위해 어떻게 초기화되고 조작되는지 조사하는 것을 고려해 볼 수 있다. 여기에는 모델에서 이러한 텐서를 만드는 데 필요한 특정 계층과 작업이 포함될 수 있다.

요약하면, 경고는 메모리 레이아웃의 잠재적인 비효율성에 관한 것이지만, 모델의 정확성 문제를 나타내는 것은 아니다. 성능이 중요한 문제라면, 이 스트라이드 불일치를 해결하기 위해 모델의 구현을 자세히 들여다보는 것이 좋을 수도 있다.

'블루아카이브' 카테고리의 다른 글

HeadHunter 구조 살펴보기  (0) 2023.01.05
BERT & RoBERTa & CORD & NER  (0) 2022.12.17
Visual Transformer  (0) 2022.08.22
레이더 Tracking 로직 & 퍼지논리  (0) 2022.02.14
자율주행의 '센서퓨전' & 센서환경 인지  (0) 2022.02.08