__call__ vs __init__

SON·2026년 3월 6일

https://huggingface.co/docs/transformers/v5.3.0/en/model_doc/siglip#transformers.SiglipTokenizer

import requests
from transformers import AutoProcessor, AutoModel
import torch

# model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
# processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")


from transformers import SiglipModel, SiglipProcessor

model = SiglipModel.from_pretrained("google/siglip-base-patch16-224")
processor = SiglipProcessor.from_pretrained("google/siglip-base-patch16-224")


url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)

candidate_labels = ["2 cats", "2 dogs"]
texts = [f'This is a photo of {label}.' for label in candidate_labels]
inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")

with torch.no_grad():
    outputs = model(**inputs)

logits_per_image = outputs.logits_per_image
probs = torch.sigmoid(logits_per_image) # 시그모이드 활성화 함수를 적용한 확률입니다
print(f"{probs[0][0]:.1%} that image 0 is '{candidate_labels[0]}'")
  • __init__ : 객체가 만들어질 때 처음 한 번 실행되는 초기화 함수
  • __call__ : 이미 만들어진 객체를 함수처럼 호출할 때 실행되는 함수

즉 역할이 완전히 달라.


1. __init__

이건 객체를 만들 때 실행돼.

예시:

class Dog:
    def __init__(self, name):
        self.name = name
        print("init 실행")

d = Dog("Coco")

실행 흐름:

  • Dog("Coco") 호출
  • 객체 생성
  • __init__(self, "Coco") 실행
  • self.name = "Coco" 저장

여기서 __init__는 보통:

  • 변수 저장
  • 옵션 설정
  • 초기 상태 만들기

를 담당해.

“객체 세팅 담당” 이야.


2. __call__

이건 객체를 함수처럼 쓸 때 실행돼.

예시:

class Dog:
    def __init__(self, name):
        self.name = name

    def __call__(self):
        print(f"{self.name} is barking")
        
d = Dog("Coco")
d()

여기서:

  • d = Dog("Coco")__init__ 실행
  • d()__call__ 실행

객체인데 함수처럼 부를 수 있게 해주는 메서드야.


3. 차이를 한 번에 보기

__init__

d = Dog("Coco")

이때 실행됨.

__call__

d()

이때 실행됨.


4. SigLIP 예시로 연결하면

예를 들어:

processor = SiglipProcessor(image_processor, tokenizer)

이때는 __init__가 실행돼.

무슨 뜻이냐면:

  • image_processor 저장
  • tokenizer 저장
  • processor 객체 세팅

이걸 하는 거야.

반면:

inputs = processor(text=texts, images=image)

이건 processor(...)처럼 객체를 함수처럼 호출한 거니까
__call__이 실행되는 거야.

즉 여기서는:

  • text를 tokenizer에 넣고
  • image를 image_processor에 넣고
  • 결과를 묶어서
  • inputs를 반환

하는 식으로 동작해.


5. 비유

__init__

커피머신 설치

  • 전원 연결
  • 물 넣기
  • 원두 넣기
  • 설정 완료

__call__

커피 추출 버튼 누르기

  • 아메리카노 만들기
  • 결과 반환

즉:

  • __init__ = 준비
  • __call__ = 실행

6. 같이 있는 예제

class MyProcessor:
    def __init__(self, x):
        self.x = x
        print("init 실행")

    def __call__(self, y):
        print("call 실행")
        return self.x + y

p = MyProcessor(10)   # __init__
result = p(5)         # __call__

print(result)

실행 결과:

init 실행
call 실행
15

여기서:

  • MyProcessor(10) → 객체 만들면서 __init__
  • p(5) → 객체를 함수처럼 불러서 __call__

7. 정리

  • __init__객체 생성 시 초기화
  • __call__객체 호출 시 실행
  • processor = SiglipProcessor(...)__init__
  • processor(...)__call__

profile
Like it, and it will be the best.

0개의 댓글