Devstral 2

Devstral 2 (Mistral)

Devstral 2는 소프트웨어 엔지니어링 작업을 위한 에이전틱 LLM 패밀리예요. 도구 사용, 코드베이스 탐색, 다중 파일 편집 같은 에이전틱 워크플로우에 맞게 설계되었고, SWE-bench에서 강력한 성능을 보여줘요.

Devstral 2 Instruct 체크포인트는 지시 튜닝된 FP8 모델로, 채팅, 도구 사용 에이전트, 지시 수행 SWE 워크로드에 잘 맞아요.

출처: 문서

본문

1. Model Introduction

Devstral 2는 소프트웨어 엔지니어링 작업을 위한 에이전틱 LLM 패밀리예요. 도구 사용, 코드베이스 탐색, 다중 파일 편집 같은 에이전틱 워크플로우를 위해 설계되었고, SWE-bench에서 강력한 성능을 보여줘요.

Devstral 2 Instruct 체크포인트는 지시 튜닝된 FP8 모델로, 채팅, 도구 사용 에이전트, 지시 수행 SWE 워크로드에 잘 맞아요.

주요 특징:

  • 에이전틱 코딩: 도구 기반 코딩과 소프트웨어 엔지니어링 에이전트에 최적화됨
  • 개선된 성능: 이전 Devstral 모델 대비 한 단계 더 나아진 성능
  • 더 나은 일반화: 다양한 프롬프트와 코딩 환경에 걸쳐 더 견고함
  • 긴 컨텍스트: 최대 256K 컨텍스트 윈도우

사용 사례: AI 코드 어시스턴트, 에이전틱 코딩, 그리고 깊은 코드베이스 이해와 도구 통합이 필요한 소프트웨어 엔지니어링 작업.

특수 기능(컨텍스트 증가, 도메인 특화 지식 등)이 필요한 기업은 Mistral에 문의해 주세요.

모델:


2. SGLang Installation

SGLang은 여러 설치 방법을 제공해요. 하드웨어 플랫폼과 요구사항에 따라 가장 적합한 설치 방법을 선택할 수 있어요.

설치 지침은 공식 SGLang 설치 가이드를 참고해 주세요.

Devstral 2는 최신 `transformers`가 필요해요. `transformers >= 5.0.0.rc`를 확인해 주세요:
python -c "import transformers; print(transformers.__version__)"

버전이 낮다면 업그레이드하세요:

pip install -U --pre "transformers>=5.0.0rc0"

3. Model Deployment

3.1 Basic configuration

대화형 명령 생성기: 아래 설정 선택기를 사용해 Devstral Small 2 (24B) 또는 Devstral 2 (123B)의 실행 명령을 생성해 보세요.

TP 크기는 선택한 모델 크기에 필요한 최소값으로 설정됩니다.

3.2 Configuration tips

  • 컨텍스트 길이 vs 메모리: Devstral 2는 긴 컨텍스트 윈도우를 제공한다고 알려져 있어요. 메모리가 부족하다면 --context-length(예: 32768)를 낮추는 것부터 시작하고, 안정되면 다시 늘려 보세요.
  • FP8 체크포인트: Devstral Small 2와 Devstral 2 모두 FP8 가중치로 배포됩니다. 커널/dtype 문제가 발생하면 더 새로운 SGLang 빌드와 최신 CUDA 드라이버를 시도해 보세요.

4. Model Invocation

4.1 Basic Usage (OpenAI-Compatible API)

SGLang은 OpenAI 호환 엔드포인트를 제공해요. 예시:

from openai import OpenAI

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

resp = client.chat.completions.create(
    model="mistralai/Devstral-Small-2-24B-Instruct-2512",
    messages=[
        {"role": "system", "content": "You are a helpful coding assistant."},
        {"role": "user", "content": "Write a Python function that retries a request with exponential backoff."},
    ],
    temperature=0.2,
    max_tokens=512,
)

print(resp.choices[0].message.content)

출력 예시:

  Here's a Python function that implements exponential backoff for retrying a request. This function uses the `requests` library to make HTTP requests and includes error handling for common HTTP and connection errors.

  ```python
  import time
  import requests
  from requests.exceptions import RequestException

  def retry_with_exponential_backoff(
      url,
      max_retries=3,
      initial_delay=1,
      backoff_factor=2,
      method="GET",
      **kwargs
  ):
      """
      Retry a request with exponential backoff.

      Parameters:
      - url: The URL to request.
      - max_retries: Maximum number of retry attempts (default: 3).
      - initial_delay: Initial delay in seconds (default: 1).
      - backoff_factor: Multiplier for the delay between retries (default: 2).
      - method: HTTP method to use (default: "GET").
      - **kwargs: Additional arguments to pass to the request function (e.g., headers, data, etc.).

      Returns:
      - Response object if the request succeeds.
      - Raises an exception if all retries fail.
      """
      retry_count = 0
      delay = initial_delay

      while retry_count < max_retries:
          try:
              response = requests.request(method, url, **kwargs)
              # Check if the response status code indicates success
              if response.status_code < 400:
                  return response
              else:
                  raise RequestException(f"HTTP {response.status_code}: {response.text}")

          except RequestException as e:
              if retry_count == max_retries - 1:
                  raise Exception(f"All retries failed. Last error: {e}")

              print(f"Attempt {retry_count + 1} failed. Retrying in {delay} seconds...")
              time.sleep(delay)
...

4.2 Tool calling (optional)

Devstral 2는 도구 호출 기능을 지원해요. 도구 호출 파서를 활성화하세요:

python -m sglang.launch_server \
  --model mistralai/Devstral-2-123B-Instruct-2512 \
  --tp 2 \
  --tool-call-parser mistral

Python 예시 (Thinking Process 포함):

from openai import OpenAI

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

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="mistralai/Devstral-2-123B-Instruct-2512",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Accumulate tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================\n", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"🔧 Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()

출력 예시:

🔧 Tool Call: get_weather
   Arguments: {"location": "Beijing"}

AMD GPU Support

1. Model Deployment

이 섹션은 다양한 하드웨어 플랫폼과 사용 사례에 최적화된 배포 구성을 제공해요.

1.1 Basic Usage

기본 API 사용법과 요청 예시는 다음을 참고하세요:

1.2 Advanced Usage

python3 -m sglang.launch_server \
  --model-path mistralai/Devstral-2-123B-Instruct-2512 \
  --tp 8 \
  --trust-remote-code \
  --port 8888

2.Benchmark

5.1 Benchmark Commands

시나리오 1: Chat (1K/1K) - 가장 중요

  • 모델 배포
python3 -m sglang.launch_server \
  --model-path mistralai/Devstral-2-123B-Instruct-2512 \
  --tp 8 \
  --trust-remote-code \
  --port 8888
  • 낮은 동시성 (지연 시간 최적화)
python3 -m sglang.bench_serving \
  --backend sglang \
  --model mistralai/Devstral-2-123B-Instruct-2512 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf \
  --port 8888
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  94.30
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4206
Request throughput (req/s):              0.11
Input token throughput (tok/s):          64.70
Output token throughput (tok/s):         44.75
Peak output token throughput (tok/s):    82.00
Peak concurrent requests:                2
Total token throughput (tok/s):          109.44
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   9427.59
Median E2E Latency (ms):                 5637.23
---------------Time to First Token----------------
Mean TTFT (ms):                          4253.85
Median TTFT (ms):                        116.95
P99 TTFT (ms):                           37764.48
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          12.28
Median TPOT (ms):                        12.29
P99 TPOT (ms):                           12.30
---------------Inter-Token Latency----------------
Mean ITL (ms):                           12.29
Median ITL (ms):                         12.29
P95 ITL (ms):                            12.38
P99 ITL (ms):                            12.42
Max ITL (ms):                            12.90
==================================================
  • 중간 동시성 (균형)
python -m sglang.bench_serving \
  --backend sglang \
  --model mistralai/Devstral-2-123B-Instruct-2512 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf \
  --port 8888
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  52.11
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  40805
Total generated tokens (retokenized):    40761
Request throughput (req/s):              1.54
Input token throughput (tok/s):          761.31
Output token throughput (tok/s):         783.13
Peak output token throughput (tok/s):    1120.00
Peak concurrent requests:                20
Total token throughput (tok/s):          1544.44
Concurrency:                             13.60
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   8856.19
Median E2E Latency (ms):                 9314.71
---------------Time to First Token----------------
Mean TTFT (ms):                          398.80
Median TTFT (ms):                        127.81
P99 TTFT (ms):                           1500.32
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          17.32
Median TPOT (ms):                        16.90
P99 TPOT (ms):                           32.78
---------------Inter-Token Latency----------------
Mean ITL (ms):                           16.61
Median ITL (ms):                         14.26
P95 ITL (ms):                            15.07
P99 ITL (ms):                            114.46
Max ITL (ms):                            1224.45
==================================================
  • 높은 동시성 (처리량 최적화)
python -m sglang.bench_serving \
  --backend sglang \
  --model mistralai/Devstral-2-123B-Instruct-2512 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf \
  --port 8888
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  116.08
Total input tokens:                      249831
Total input text tokens:                 249831
Total input vision tokens:               0
Total generated tokens:                  252662
Total generated tokens (retokenized):    252523
Request throughput (req/s):              4.31
Input token throughput (tok/s):          2152.21
Output token throughput (tok/s):         2176.60
Peak output token throughput (tok/s):    3600.00
Peak concurrent requests:                107
Total token throughput (tok/s):          4328.81
Concurrency:                             92.42
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   21456.71
Median E2E Latency (ms):                 20126.82
---------------Time to First Token----------------
Mean TTFT (ms):                          291.60
Median TTFT (ms):                        199.24
P99 TTFT (ms):                           866.02
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          42.42
Median TPOT (ms):                        45.18
P99 TPOT (ms):                           53.32
---------------Inter-Token Latency----------------
Mean ITL (ms):                           41.97
Median ITL (ms):                         27.59
P95 ITL (ms):                            130.43
P99 ITL (ms):                            137.87
Max ITL (ms):                            616.73
==================================================

5.2 Understanding the Results

주요 지표:

  • Request Throughput (req/s): 초당 처리되는 요청 수
  • Output Token Throughput (tok/s): 초당 생성되는 총 토큰 수
  • Mean TTFT (ms): Time to First Token - 응답성을 측정
  • Mean TPOT (ms): Time Per Output Token - 생성 속도를 측정
  • Mean ITL (ms): Inter-Token Latency - 스트리밍 일관성을 측정

이 구성이 중요한 이유:

  • 1K/1K (Chat): 가장 흔한 대화형 AI 워크로드를 나타내요. 대부분의 배포에서 최우선 시나리오예요.
  • 1K/8K (Reasoning): 복잡한 추론, 코드 생성, 상세한 설명에 필수적인 장문 생성 능력을 테스트해요.
  • 8K/1K (Summarization): RAG 시스템, 문서 Q&A, 요약 작업에 필수적인 대형 컨텍스트 입력 성능을 평가해요.
  • 가변 동시성: 서로 다른 부하 수준에서 처리량과 지연 시간 사이의 최적 트레이드오프인 Pareto frontier를 포착해요. 낮은 동시성은 최상의 지연 시간을, 높은 동시성은 최대 처리량을 보여줘요.

결과 해석:

  • 결과를 하드웨어의 기준 수치와 비교해 보세요
  • 같은 지연 시간에서 더 높은 처리량 = 더 나은 성능
  • 더 낮은 TTFT = 더 반응성 높은 사용자 경험
  • 더 낮은 TPOT = 더 빠른 생성 속도

5.3 Accuracy Benchmark

표준 벤치마크에서 모델 정확도를 문서화합니다:

5.3.1 GSM8K Benchmark

  • 벤치마크 명령
python3 benchmark/gsm8k/bench_sglang.py \
  --num-shots 8 \
  --num-questions 1316 \
  --parallel 1316 \
  --port 8888

테스트 결과:

Accuracy: 0.922
Invalid: 0.000
Latency: 35.800 s
Output throughput: 4507.697 token/s

더 알아보기