LLM SLM 공부하기 전 일단 돌려보자.. copilot에게 모든 코딩을 부탁해 보았다.
전체 코드
"""
SmolLM 추론 코드 - 실제 모델 버전
HuggingFace의 SmolLM-135M 모델을 사용합니다.
"""
import warnings
warnings.filterwarnings("ignore")
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
class SmolLMInference:
def __init__(self, model_name="HuggingFaceTB/SmolLM-135M"):
"""
SmolLM 모델 초기화
Args:
model_name: 사용할 SmolLM 모델명 (기본값: 가장 작은 135M 모델)
"""
self.model_name = model_name
print(f"모델 로딩 중: {model_name}")
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"사용 디바이스: {self.device}")
# 토크나이저와 모델 로드
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None
)
# 패딩 토큰이 없으면 EOS 토큰을 패딩 토큰으로 설정
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
print("모델 로딩 완료!")
def generate_text(self, prompt, max_length=100, temperature=0.7, do_sample=True, top_p=0.9):
"""
텍스트 생성 함수
Args:
prompt: 입력 프롬프트
max_length: 최대 생성 길이
temperature: 샘플링 온도 (높을수록 창의적)
do_sample: 샘플링 여부
top_p: nucleus sampling 파라미터
Returns:
생성된 텍스트
"""
# 입력 텍스트 토크나이징
inputs = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
# 텍스트 생성
with torch.no_grad():
outputs = self.model.generate(
inputs,
max_length=max_length,
temperature=temperature,
do_sample=do_sample,
top_p=top_p,
pad_token_id=self.tokenizer.eos_token_id,
num_return_sequences=1
)
# 생성된 텍스트 디코딩
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
# 원본 프롬프트 제거하고 생성된 부분만 반환
if generated_text.startswith(prompt):
generated_text = generated_text[len(prompt):].strip()
return generated_text
def main():
"""메인 실행 함수"""
print("=== SmolLM 추론 데모 ===")
print("(HuggingFace SmolLM-135M 모델)")
# SmolLM 인스턴스 생성
try:
llm = SmolLMInference()
except Exception as e:
print(f"초기화 에러: {e}")
return
# 예시 프롬프트들
example_prompts = [
"The weather today is",
"Python is a programming language that",
]
print("\n=== 예시 추론 결과 ===")
for i, prompt in enumerate(example_prompts, 1):
print(f"\n{i}. 프롬프트: '{prompt}'")
try:
generated = llm.generate_text(
prompt=prompt,
max_length=50, # 짧은 생성을 위해 길이 제한
temperature=0.8
)
print(f" 생성 결과: {prompt} {generated}")
except Exception as e:
print(f" 생성 에러: {e}")
# 대화형 모드
print("\n=== 대화형 모드 (종료하려면 'quit' 입력) ===")
while True:
try:
user_prompt = input("\n프롬프트를 입력하세요: ")
if user_prompt.lower() in ['quit', 'exit', '종료']:
break
if user_prompt.strip():
generated = llm.generate_text(
prompt=user_prompt,
max_length=100,
temperature=0.7
)
print(f"생성 결과: {user_prompt} {generated}")
else:
print("빈 프롬프트입니다. 다시 입력해주세요.")
except KeyboardInterrupt:
print("\n프로그램을 종료합니다.")
break
except Exception as e:
print(f"에러 발생: {e}")
if __name__ == "__main__":
main()
결과
=== SmolLM 추론 데모 ===
(HuggingFace SmolLM-135M 모델)
모델 로딩 중: HuggingFaceTB/SmolLM-135M
사용 디바이스: cuda
모델 로딩 완료!
=== 예시 추론 결과 ===
1. 프롬프트: 'The weather today is'
The attention mask is not set and cannot be inferred from input because pad token is same as eos token. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
생성 결과: The weather today is still wet and warm and there are still some cloudy days.
- The weather is forecasted to be warm and dry and there is still a lot of sunshine.
- The weather is forecasted to be cold and dry and
2. 프롬프트: 'Python is a programming language that'
생성 결과: Python is a programming language that can be used for a variety of tasks, such as web development, mobile app development, and data analysis. Python is known for its readability and simplicity, making it a popular choice for beginners and experienced programmers alike.
=== 대화형 모드 (종료하려면 'quit' 입력) ===
프롬프트를 입력하세요: explain about smolLM
생성 결과: explain about smolLM and the models that it can use to predict the future.
Now that we have a basic understanding of how the models work, let's move on to the main part of the project: training the models.
### Training the Models
The first step in training the models is to load the data. This data can come from various sources, such as the training data, the testing data, or the validation data. For this project, we will be
프롬프트를 입력하세요: where is south korea
생성 결과: where is south korea , and the northern part of the country.
The main source of water is from the lake. The lake is located in the south of the country and the water is of great importance for the water supply and irrigation. The lake is the largest lake in the country.
The lake is also a great source of fish, which is an important source of protein for many people. The lake is the largest lake in the country and it is located in the south of the
프롬프트를 입력하세요: quit
SmolLM & 코드 설명
SmolLM이란?
SLM = Small Language Model (소형 언어 모델)
- ChatGPT같은 거대한 모델과 달리 작고 가벼운 모델
- 135M = 1억 3천 5백만 개의 파라미터 (ChatGPT는 수천억 개)
- 개인 컴퓨터에서도 실행 가능한 크기
trasnsformers 라이브러리
from transformers import AutoTokenizer, AutoModelForCausalLM
HuggingFace에서 만든 Python 라이브러리이다.
- 사전 훈련된 모델들을 쉽게 사용할 수 있게 해줌
- BERT, GPT, T5, SmolLM 등 수천 개의 모델 지원
- 복잡한 AI 모델을 몇 줄의 코드로 사용 가능
토크나이저란?
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
사람이 읽는 텍스트 → 컴퓨터가 이해하는 숫자로 변환
예: "Hello" → [15496] 같은 숫자로 변환
각 단어나 글자 조각을 "토큰"이라고 부름
모델 로딩~텍스트 생성 함수
#모델 로딩
self.model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None
)
#패딩 토큰 설정: 문장 길이 맞추기 위해 빈 공간 표시
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
#텍스트 생성 함수
def generate_text(self, prompt, max_length=100, temperature=0.7, do_sample=True, top_p=0.9):
텍스트 생성 함수 파라미터 설명:
- prompt: 입력 텍스트 (시작하는 문장)
- max_length: 최대 생성할 글자 수
- temperature: 창의성 조절 (0~1, 높을수록 창의적)
- do_sample: 랜덤성 추가 여부
- top_p: 다양성 조절 (0~1, 높을수록 다양함)
Encode(텍스트->토큰(숫자)), Decode(토큰->텍스트)
inputs = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
Temperature란?
Temperature는 AI 모델이 얼마나 "창의적"이거나 "예측 가능한" 텍스트를 생성할지를 조절하는 매개변수입니다.
온도계와의 비유
실제 온도계처럼 생각해보세요:
낮은 온도 (추위): 분자들이 천천히, 규칙적으로 움직임 → 예측 가능함
높은 온도 (더위): 분자들이 빠르게, 무작위로 움직임 → 예측 불가능함
0.7의 temperature를 많이 사용한다.
'DeepLearning' 카테고리의 다른 글
| [Ollama] vs pytorch transformers (3) | 2025.08.11 |
|---|---|
| [aws ec2] vscode 연결: config 설정, 인스턴스 용량 증설 (1) | 2025.08.11 |
| Class Imbalance (0) | 2022.12.26 |
| Diffusion Model - 개념 알기 (0) | 2022.10.11 |
| [논문리뷰] CutPaste: Self-Supervised Learning for Anomaly Detection and Localization (0) | 2022.08.04 |