Skip to content

실전 예제를 상징하는 이미지

앞선 가이드에서 모델의 특징과 실행 방법, 그리고 최적의 프롬프트 전략을 살펴보았습니다. 이제 이 모든 내용을 종합하여 실제 서비스나 업무 환경에 적용할 수 있는 구체적인 코드 레시피를 소개합니다. 모든 예제는 공식 README의 영어 프롬프트 패턴을 한국어 번역 시나리오에 맞춰 최적화한 것입니다.

기본 영어 $\rightarrow$ 한국어 번역 구현 ​

transformers 라이브러리를 사용하여 모델을 직접 구동하는 가장 표준적인 방법입니다. 30B-A3B의 권장 파라미터(temperature=0.7, top_p=1.0, top_k=-1, repetition_penalty=1.0)를 적용해 일관된 품질의 결과를 얻도록 구성했습니다.

python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_path = "tencent/Hy-MT2-30B-A3B"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    dtype=torch.bfloat16,
    device_map="auto",
    trust_remote_code=True,
)
model.eval()

def translate(text: str, target_lang: str) -> str:
    # 공식 패턴: 대상 언어 명시 + 추가 설명 금지 지시
    prompt = (
        f"Translate the following text into {target_lang}. Note that you should "
        f"only output the translated result without any additional explanation:\n\n{text}"
    )
    messages = [{"role": "user", "content": prompt}]
    inputs = tokenizer.apply_chat_template(
        messages, add_generation_prompt=True, return_tensors="pt"
    ).to(model.device)
    
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=4096,
            temperature=0.7,
            top_p=1.0,
            top_k=-1,
            repetition_penalty=1.0,
        )
    return tokenizer.decode(
        outputs[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True
    )

print(translate("The weather is really nice today.", "Korean"))
# 출력 예: 오늘 날씨가 정말 좋네요.

Tip: 한국어에서 영어로 번역하고 싶다면 target_lang을 "English"로 변경하세요. 만약 프롬프트 자체를 한국어로 작성하신다면, 언어 이름 역시 한국어(영어, 한국어)로 적는 것이 모델의 성능을 높이는 방법입니다.

정확도를 높이는 용어 목록(Glossary) 주입 ​

기업 내부의 고유 용어나 정해진 역어가 있는 경우, 번역할 텍스트 앞에 참고 번역 짝을 제공하여 오역을 방지할 수 있습니다.

python
# 조직 내 표준 용어집 정의
GLOSSARY = [
    ("inference server", "추론 서버"),
    ("cache hit rate", "캐시 적중률"),
    ("throughput", "처리량"),
]

def translate_with_glossary(text: str, glossary) -> str:
    # 용어집을 "원문" translates to "역어" 형태로 변환
    refs = "\n".join(f'"{src}" translates to "{dst}"' for src, dst in glossary)
    prompt = (
        f"Reference the following translations:\n{refs}\n\n"
        f"Translate the following text into Korean. Note that you must "
        f"ONLY output the translated result without any additional explanation:\n\n{text}"
    )
    # 이후 process는 기본 translate 함수와 동일
    ...

용어 목록이 지나치게 길어지면 모델의 컨텍스트 창(8192 토큰)을 압박하고 오히려 품질이 떨어질 수 있습니다. 현재 번역하려는 문단에 꼭 필요한 핵심 용어 위주로 선별해 넣는 것을 권장합니다.

데이터 무결성을 위한 JSON 구조 보존 번역 ​

앱의 다국어 리소스 파일(JSON)을 번역할 때는 키(Key)나 플레이스홀더가 훼손되지 않는 것이 가장 중요합니다. 이를 위해 엄격한 구조 보존 지시문을 함께 전달합니다.

python
source_json = '{"title": "Welcome", "message": "Hello, ${user_name}!", "button": "Continue"}'

prompt = f"""### Task
Translate the user-facing text within the following JSON data into Korean.

### Strict Rules
1. Structure Preservation: You MUST preserve the original JSON data structure, nesting, hierarchy, and indentation exactly as they are.
2. Selective Translation: Translate ONLY the visible, user-facing text content/values.
3. Strict Non-Translation: NEVER translate or alter code tags, keys, properties, object names, or variable placeholders. Leave them exactly in their original English/code form.

### Source Data
{source_json}"""

이 방식을 사용하면 ${user_name}과 같은 변수는 그대로 유지하면서 값만 "안녕하세요, ${user_name}님!"과 같이 번역됩니다. 실제 서비스에 적용할 때는 결과물을 json.loads로 파싱해 구조적 결함이 없는지 검증하는 로직을 추가하는 것이 안전합니다.

문맥을 유지하는 여러 문장 배치 번역 ​

긴 문서를 번역할 때 단순히 문장별로 호출하면 대명사나 호칭 등이 어긋나는 경우가 많습니다. 이를 해결하기 위해 이전 문장의 번역 결과를 다음 문장의 배경 정보로 넘겨주는 방식을 추천합니다.

python
paragraphs = [
    "The Core is waking up.",
    "It has been asleep for thirty years.",
]

# 전체적인 문맥 정보 설정
context = "This dialogue is from a sci-fi movie. 'The Core' is the name of a supercomputer."
for para in paragraphs:
    prompt = (
        f"[Background Information]\n{context}\n\n"
        f"[Source Text]\n{para}\n\n"
        f"Please translate the following text into Korean, taking the provided "
        f"background information into consideration."
    )
    result = translate_raw(prompt) 
    print(result)
    # 현재 번역 결과를 다음 문장의 배경 정보에 누적
    context += f"\nPrevious translation: {result}"

이렇게 하면 "It(그것)"이 무엇을 가리키는지 모델이 인지하게 되어, 훨씬 매끄러운 문맥 연결이 가능해집니다.

vLLM OpenAI 호환 API로 효율적으로 호출하기 ​

실행 가이드를 통해 vLLM 서버를 구축했다면, 기존의 OpenAI SDK를 그대로 사용할 수 있어 통합 비용이 매우 낮아집니다.

curl을 이용한 직접 호출:

bash
curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "tencent/Hy-MT2-30B-A3B",
    "messages": [
      {"role": "user", "content": "Translate the following text into Korean. Note that you should only output the translated result without any additional explanation:\n\nMachine translation has changed the shape of the localization industry."}
    ],
    "temperature": 0.7,
    "top_p": 1.0,
    "max_tokens": 4096
  }'

Python OpenAI 클라이언트 활용:

python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")

resp = client.chat.completions.create(
    model="tencent/Hy-MT2-30B-A3B",
    messages=[
        {
            "role": "user",
            "content": (
                "Translate the following text into Korean. Note that you should "
                "only output the translated result without any additional explanation:\n\n"
                "Machine translation has changed the shape of the localization industry."
            ),
        }
    ],
    temperature=0.7,
    max_tokens=4096,
)
print(resp.choices[0].message.content)

이로써 Hy-MT2-30B-A3B의 소개부터 실행, 최적의 프롬프트 전략, 그리고 실전 구현까지 모든 과정을 살펴보았습니다. 더 자세한 기술적 분석은 Hy-MT2 리포트와 공식 저장소를 통해 확인하실 수 있습니다.

오픈소스를 한국어로 읽고 배웁니다.