최근에 삼성 ssd t7을 구매했다. 

내 맥북 스펙은 다음과 같다.

인텔 맥북 프로, sonoma 14.4.1

잘 사용하고 있던 찰나 어느 순간부터 외장하드 인식이 너무 느렸다. 20~30분을 기다려야만 인식이 되고 접근이 가능했다.

도저히 이유를 알 수가 없어서 여러가지 시도를 해본 결과 아래 링크에서 해결 방법을 찾았고 효과는 대단했다!

https://www.reddit.com/r/MacOS/comments/192kjts/extremely_slow_external_ssd_on_macos_ventura/

시스템 설정 - Siri 및 Spotlgihjt - 제일 하단으로 이동 - Spotlight 개인 정보 보호 - 외장하드 등록

위 작업을 수행하니 추출 후 다시 꼽았을 때 딜레이 없이 바로 인식 되는 것을 확인했다!!!!!!!! 

등록한 결과 이미지

docker pull mongo:6.0.13
docker run --name mongodb-test -p 27017:27017 -v /pathtodb:/data/db -d mongo:6.0.13

 

Ubuntu Jammy = Ubuntu 22.04 LTS

그냥 버전 가르키는 코드 명

REFERENCE

1. prepare_data

  • 데이터 다운로드 등의 기능을 수행할 메서드.
  • setup 전에 호출 됨.
  • main process + single process니까 device 별 실행 되야하는 기능은 해당 메서드에서 구현을 피해야 함.
  • DO NOT set state to the model (use setup instead) since this is NOT called on every device
    (e.g. self.split='train')

2. setup


 

아래처럼 깔끔하게 사용할 수도 있지만, Dataset등의 내부 멤버 변수가 필요하면 수동으로 콜해도 문제 없다.

dm = MNISTDataModule()
model = Model()
trainer.fit(model, datamodule=dm)
trainer.test(datamodule=dm)
trainer.validate(datamodule=dm)
trainer.predict(datamodule=dm)
dm = MNISTDataModule()
dm.prepare_data()
dm.setup(stage="fit")

model = Model(num_classes=dm.num_classes, width=dm.width, vocab=dm.vocab)
trainer.fit(model, dm)

dm.setup(stage="test")
trainer.test(datamodule=dm)

 

Save

torch.save(model.state_dict(), PATH)

보통 torch.save를 사용해서 pytorch model을 저장하는데 이때 보통 .pt, .pth의 확장자를 쓴다. 그러나 .pth의 경우 python path와 충돌 위험이 있기때문에 .pt 확장자를 사용하는 것을 추천한다. 

Save for resume

torch.save({
            'epoch': epoch,
            'model_state_dict': model.state_dict(),
            'optimizer_state_dict': optimizer.state_dict(),
            'loss': loss,
            ...
            }, PATH)

일반적으로 모델을 저장할 때 학습 재개(resuming)를 위해 모델 파라미터 뿐만 아니라 optimizer, loss, epoch, scheduler등 다양한 정보를 함께 저장한다. 그래서 이러한 checkpoint는 모델만 저장할 때에 비해서 용량이 훨씬 커진다. 이럴때는 .tar 확장자를 사용한다. 나는 주로 .pth.tar를 사용한다.

To save multiple components, organize them in a dictionary and use torch.save() to serialize the dictionary. A common PyTorch convention is to save these checkpoints using the .tar file extension.

reference

'Deep Learning > pytorch' 카테고리의 다른 글

torch.backends.cudnn.benchmark = True 의미  (0) 2021.08.23
[Pytorch] yolo to pytorch(0)  (0) 2021.05.17
# TENSORRT
set(TRT_VERSION 7.2.3.4)
set(TRT_PATH "path to tensorrt"/TensorRT-${TRT_VERSION})

# TensorRT
MESSAGE("\nTensorRT " ${TRT_VERSION})
MESSAGE(STATUS "${TRT_PATH}\n")

set(TRT_INCLUDE_PATH ${TRT_PATH}/include)
set(TRT_LIB_PATH ${TRT_PATH}/lib)
set(TRT_LIBS nvinfer nvonnxparser)
set(TRT_DLLS ${TRT_LIB_PATH}/nvinfer.dll
			 ${TRT_LIB_PATH}/nvonnxparser.dll
			 ${TRT_LIB_PATH}/nvinfer_plugin.dll
			 ${TRT_LIB_PATH}/myelin64_1.dll
			 )
include_directories(${TRT_INCLUDE_PATH})
link_directories(${TRT_LIB_PATH})
link_libraries(${TRT_LIBS})

# do something 
# ...
# ...

# when build excutable
add_custom_command(TARGET ${project}
				   POST_BUILD
				   COMMAND ${CMAKE_COMMAND} -E copy 
				   ${TRT_DLLS}
				   ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${CMAKE_BUILD_TYPE}
)

예전에 vscode-ssh로 서버에 연결하려고 할 때, XHR failed가 뜨면서 문제가 됐던적이있다.

검색해보니 DNS문제 등등 다양한 문제가 있었는데 내 경우는 서버가 인터넷에 연결이 안되어있어서 필요한 vscode-server를 다운받지 못하는 문제인것으로 예상했다.

그래서 정말 다양한 방법을 시도해봤는데 결국 포기했다가 아래 링크를 찾았다. 

https://stackoverflow.com/questions/56671520/how-can-i-install-vscode-server-in-linux-offline

ssh 연결할때 뜨는 커밋 아이디가 있는데

위 이슈에 있는 링크에서 해당 커밋아이디의 파일을 다운받고

~/.vscode-server/bin/(commid id) 폴더에 해당 파일은 unzip하니 해결됐다

디테일한 명령어는 위 링크대로 따라했고 연결에 성공했다.

거의 일주일간의 삽질을 위 방법으로 해결할 수 있었다.

'Deep Learning > 기타' 카테고리의 다른 글

coco label items  (0) 2021.08.11
Darknet validationset 학습 포함 여부  (0) 2021.07.29

개인적으로 읽고 쓰는 공부용 리뷰입니다.

틀린 점이 있을 수도 있으니 감안하고 읽어주세요. 피드백은 댓글로 부탁드립니다.

[TensorRT] 1. Build tensorrt engine (tensorRT 7.2.3)


Serializie는 나중에 재사용을 위해 저장하기위한 포맷으로 바꾸는 것을 의미한다. inference에 사용하기 위해서는 그냥 deserializie한 뒤 쓰면 된다. 보통 빌드과정이 시간을 소요하기 때문에 매번 빌드하는 것을 피하기 위해 이 과정을 한다.

// code for serializing ICudaEngine
IHostMemory *serializedModel = engine->serialize();
// store model to disk
// <…>
 serializedModel->destroy();

-

Deserialize code, The final argument is a plugin layer factory for applications using custom layers. For more information, see [Extending TensorRT With Custom Layers]
별거아니고, 마지막에 nullptr는 iplugin for custom layer인데 없다면 그냥 nullptr넣으면 된다.

// code for deserializing ICudaEngine
IRuntime* runtime = createInferRuntime(gLogger);
ICudaEngine* engine = runtime->deserializeCudaEngine(modelData, modelSize, nullptr)

주의 할점은 trt version, gpu, platform을 항시 잘 체크해야한다.

  • Serialized engines are not portable across platforms or TensorRT versions.
  • Engines are specific to the exact GPU model they were built on.

 

위에는 tensorrt reference의 코드인데 처음에보고 어떻게 더 추가해야할지 몰라서 막막했다.
아래는 실제로 내가 사용하는 serializing & save 코드다.

여기서 engine_ 은 빌드가 성공적으로 된 ICudaEngine이다.

bool saveEngine( std::string &fileName ) const 
{
    std::ofstream engineFile( fileName, std::ios::binary );
    if ( !engineFile ) {
        gLogFatal << "Cannot open engine file : " << fileName << std::endl;
        return false;
    }

    if ( engine_ == nullptr ) {
        gLogError << "Engine is not defined" << std::endl;
        return false;
    }
    nvinfer1::IHostMemory *serializedEngine{engine_->serialize()};
    if ( serializedEngine == nullptr ) {
        gLogError << "Engine serialization failed" << std::endl;
        return false;
    }

    engineFile.write( static_cast<char *>( serializedEngine->data() ),
                      serializedEngine->size() );
    if ( engineFile.fail() ) {
        gLogError << "Failed to save Engine." << std::endl;
        return false;
    }
    std::cout << "Successfully save to : " << fileName << std::endl;
    return true;
}

 

다음은 저장된 ICudaEngine을 load후 다시 deserializing하는 코드다. 

bool Load( const std::string &fileName ) {
    std::ifstream engineFile( fileName, std::ios::binary );
    if ( !engineFile ) {
        std::cout << "can not open file : " << fileName << std::endl;
        return false;
    }
    engineFile.seekg( 0, engineFile.end );
    auto fsize = engineFile.tellg();
    engineFile.seekg( 0, engineFile.beg );

    std::vector<char> engineData( fsize );
    engineFile.read( engineData.data(), fsize );

    Load( engineData.data(), ( long int )fsize );
    return true;
}

bool Load( const void *engineData, const long int fsize ) {
    nvinfer1::IRuntime *runtime = nvinfer1::createInferRuntime( gLogger.getTRTLogger() );
    engine_ = runtime->deserializeCudaEngine( engineData, fsize, nullptr );
    // if u want DLA core setting, then u shoud write code here
    runtime->destroy();
    return true;
}

두가지 방법으로 load할수있어서 오버로딩해놨다.

끝 

'Deep Learning > tensorrt' 카테고리의 다른 글

[TensorRT] 1. Build tensorrt engine (tensorRT 7.2.3)  (6) 2021.03.24

의미 그대로 cudnn의 benchmark를 통해 최적의 backend 연산을 찾는 flag를 true로 하겠단 의미.

CNN에서 대부분의 연산을 차지하는 convolution의 경우, 아래 사진의(출처의 두번째 링크) 지원하는 연산 중 최적의 알고리즘을 찾아 적용한다.

cf) 확실한 것은 아니지만 아마 이 벤치마크는 모델이 상수처럼 작동할 때 최적의 연산을 찾을 수 있을 것이다. 예를 들어서 입력크기가 고정되어 모델이 static하게 작동한다면 이 flag가 유효하겠지만, 
입력크기가 다양하거나 또는 dynamic한 연산이 모델의 fowarding에 포함된 경우는 큰 효과를 보지 못할 수도 있을 것같다. 

출처 : https://discuss.pytorch.org/t/why-does-winograd-algorithm-speedup-convolution-given-that-mul-and-add-cost-the-same-clock-cycles-on-gpu/89993/4

https://docs.nvidia.com/deeplearning/cudnn/developer-guide/index.html#tensor-ops-conv-functions-supported-algos

https://discuss.pytorch.org/t/what-does-torch-backends-cudnn-benchmark-do/5936

 

'Deep Learning > pytorch' 카테고리의 다른 글

[pytorch] save pytorch model  (0) 2021.09.15
[Pytorch] yolo to pytorch(0)  (0) 2021.05.17

coco label 얻기

ids = list(sorted(coco.imgs.keys()))
coco_idx = [ids[idx]]  # from index to coco_index
coco.loadAnns(self.coco.getAnnIds(coco_idx))

아래처럼 object별로 7개의 key값을 가짐

segmentation은 annotation type이 두개가있다.
segmentation1 : list[float], polygon 좌표 xy인데 flatten시켰다. 
segmentation2 :  a run-length-encoded (RLE) bit mask 
    'counts' :
    'size'     :

area : 객체 안에 속한 pixel 수

iscrowd :  0 또는 1, 1이면 정확도 측정할 때 제외함 

image_id : 현재 객체가 속한 image의 index, 그래서 같은 이미지에 있는 객체들은 값이 같음. (82783: coco2014train)

bbox : bounding box 좌표, 좌상단xy wh로 구성되어있으며 normalizing 안되어있음

category_id : ojbect의 class index 총 80개며 1~90사이의 값을 가짐

id : 각 object에 대한 id인데 어떻게 라벨링 되는지는 모르겠음.

 

아 category_id가 좀 다를 것이다 0~79의 80개 class가 아니라 1~90으로 나온다. 몇개 삭제된 클래스가 있다. 아래 tuple써서 치환(?)하면 됨
(255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 255, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 255, 24, 25, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 255, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 255, 60, 255, 255, 61, 255, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 255, 73, 74, 75, 76, 77, 78, 79)

 

https://github.com/cocodataset/cocoapi/issues/184

https://github.com/facebookresearch/Detectron/issues/100

https://www.immersivelimit.com/tutorials/create-coco-annotations-from-scratch

https://www.youtube.com/watch?v=h6s61a_pqfM 

 

'Deep Learning > 기타' 카테고리의 다른 글

vscode에서 서버 연결할 때, XHR failed  (0) 2021.08.26
Darknet validationset 학습 포함 여부  (0) 2021.07.29

+ Recent posts