Skip to content
CatBus
Go back

[Troubleshooting] pytorch의 IndexError: index out of range in self 에러

🚫 현상


💡원인


🛠 해결책

  1. torch.zeros_like(encodings['input_ids']):
    • 이 부분은 encodings['input_ids']와 동일한 모양과 데이터 유형을 가진 0으로 채워진 새로운 텐서를 생성합니다.
    • 따라서, 입력된 텍스트의 토큰 수와 같은 길이의 0으로만 채워진 ‘token_type_ids’ 텐서가 생성 됩니다.
  2. encodings['token_type_ids'] = ...:
    • 이렇게 생성된 0으로 채워진 텐서를 encodings['token_type_ids']에 할당합니다.
    • 결과적으로, 원래 token_type_ids에 있던 모든 값을 0으로 덮어씁니다.
  3. 단일 문장 분류:
    • 질문/답변 쌍이나 문장 A/문장 B와 같은 두 개 이상의 세그먼트를 구분할 필요가 없는 단일 문장 분류 작업에서는 token_type_ids가 실제로 필요하지 않습니다.
    • 모든 token_type_ids를 0으로 설정해도 모델은 여전히 입력 텍스트를 정확하게 처리할 수 있습니다.
def predict_single_text(text):
    # 입력 텍스트를 토큰화
    encodings = tokenizer(text, padding="max_length", truncation=True, max_length=64, return_tensors="pt")
    
    # print("Token Type IDs:", encodings['token_type_ids'])
    encodings['token_type_ids'] = torch.zeros_like(encodings['input_ids']) # <<< 여기 추가
    # print("Token Type IDs:", encodings['token_type_ids'])
    # 입력 데이터를 GPU로 이동
    encodings = {key: value.to(device) for key, value in encodings.items()}
    # 예측 수행
    model.to(device)
    with torch.no_grad():
        outputs = model(**encodings)
        logits = outputs.logits

    # 예측된 라벨을 얻기
    prediction = torch.argmax(logits, dim=-1).cpu().item()
    
    # 예측 결과를 카테고리로 변환
    predicted_category = id_to_category[prediction]
    
    return predicted_category


🤔 회고


📚 Reference


Share this post:

비슷한 글

IndexError이 글

본문을 Xenova/multilingual-e5-small 로 임베딩하고, 그 벡터를 PCA 로 32축에 눌러 왼쪽 막대로 그렸습니다. 비슷한 글은 지문도 닮습니다 — 위아래를 견줘 보세요. 계산은 빌드 때 끝나고 벡터는 브라우저로 오지 않습니다.

Previous Post
[Programmers] 대장균들의 자식의 수 구하기 - 299305
Next Post
[Programmers] 최솟값 구하기 - 59038