SWE-bench test

Run a SWE-bench to Test LLM’s Performance

1. Host Environment Preparation (Prerequisites)

Since we are using Docker to deploy vLLM, the host machine *does not need to install CUDA Toolkit*. It only requires the NVIDIA Driver and NVIDIA Container Toolkit.

Ensure your host machine has the NVIDIA driver installed. You can verify it by running:

1
nvidia-smi

(If it fails, please install the driver via sudo apt install nvidia-driver-550 or the official .run file, then reboot.)

Install Docker:

1
2
3
4
5
6
7
8
# Install Docker
sudo apt update
sudo apt install -y docker.io
sudo systemctl enable --now docker

# Add current user to docker group (to run docker without sudo)
sudo usermod -aG docker $USER
# Note: You need to log out and log back in, or run `newgrp docker` to apply this change.

Install NVIDIA Container Toolkit:

1
2
3
4
5
6
7
8
9
10
11
12
13
# Configure the repository
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list

# Install the toolkit
sudo apt update
sudo apt install -y nvidia-container-toolkit

# Configure Docker runtime
sudo nvidia-ctk runtime configure --runtime=docker
sudo systemctl restart docker

Verify GPU Access in Docker:

1
docker run --rm --gpus all nvidia/cuda:12.4.0-base-ubuntu22.04 nvidia-smi

If this command successfully prints your GPU information, your host environment is fully ready!

2. Create a Virtual Environment for SWE

* Note on CUDA Version:* The system’s default CUDA version (e.g., CUDA 13.0) is often too new and causes flashinfer JIT compilation errors (like has no member "FlagHeads"). It is highly recommend to use Docker for vLLM deployment later, but if you prefer Conda, ensure you pin the CUDA version.

1
2
3
mkdir -p /data/disk2/wye
cd /data/disk2/wye
conda create --prefix /data/disk2/wye/swe_env_cu124 python=3.10 -y

Active Conda Environment:

1
conda activate /data/disk2/wye/swe_env_cu124/

Explicitly install PyTorch with CUDA 12.4 to prevent pip from pulling CUDA 13.0 dependencies later(If use the docker, it’s not necesssary):

1
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124

3. Install SWE Code in Conda Environment

1
2
3
4
cd /data/disk2/wye
git clone --depth 1 https://github.com/princeton-nlp/SWE-bench.git
cd SWE-bench
pip install -e .

4. Download Lite Dataset

1
2
3
4
5
6
7
8
python -c "
import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
from datasets import load_dataset
print('开始下载 SWE-bench Lite 数据集...')
dataset = load_dataset('princeton-nlp/SWE-bench_Lite', split='test')
print(f'下载成功!共获取 {len(dataset)} 个测试任务。')
"

5. Download Qwen2.5-Coder-7B-Instruct

Choose a model that has been trained with instructions, like Qwen2.5-Coder-7B-Instruct.

Use modelscope to download models quickly:

1
2
3
4
pip install modelscope
mkdir -p /data/disk2/wye/models
modelscope download --model Qwen/Qwen2.5-Coder-7B-Instruct \
--local_dir /data/disk2/wye/models/Qwen2.5-Coder-7B-Instruct

6. Deploy vLLM Inference Server

Use docker to start the vLLM inference server:

1
2
3
4
5
6
7
8
9
10
docker run -d --name vllm_server --gpus all \
-v /data/disk2/wye/models:/models \
-p 8000:8000 \
--ipc=host \
vllm/vllm-openai:latest \
--model /models/Qwen2.5-Coder-7B-Instruct \
--dtype auto \
--max-model-len 16384 \
--gpu-memory-utilization 0.9 \
--port 8000

Check the logs to ensure it starts successfully:

7. Run Inference to Generate Patches

SWE-bench requires the model to output patches in a specific JSONL format. Create a file named run_inference.py, the path is /data/disk2/wye/run_inference.py :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import json
from datasets import load_dataset
from openai import OpenAI

# Connect to the vLLM server running in Docker
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")

# Load the dataset
dataset = load_dataset("princeton-nlp/SWE-bench_Lite", split="test")

predictions = []
# For testing purposes, we only run the first 3 instances.
# Change to len(dataset) for a full run.
for i, item in enumerate(dataset):
if i >= 3:
break

instance_id = item["instance_id"]
problem_statement = item["problem_statement"]

prompt = f"""You are an expert software engineer. Please fix the following GitHub issue.
Output ONLY the unified diff patch. Do not include any explanations or markdown formatting.

Issue:
{problem_statement}
"""

response = client.chat.completions.create(
model="/models/Qwen2.5-Coder-7B-Instruct",
messages=[{"role": "user", "content": prompt}],
temperature=0.0,
max_tokens=4096
)
patch = response.choices[0].message.content

# ⚠️ CRITICAL: SWE-bench requires 'model_name_or_path' field in the JSONL
predictions.append({
"instance_id": instance_id,
"model_patch": patch + "\n",
"model_name_or_path": "Qwen2.5-Coder-7B-Instruct"
})

# Save as jsonl
with open("predictions.jsonl", "w", encoding="utf-8") as f:
for pred in predictions:
f.write(json.dumps(pred) + "\n")

print("Inference completed. Saved to predictions.jsonl")

Run the script to get the path:

1
python run_inference.py

8. Run SWE-bench Evaluation

The evaluation phase strictly requires Docker to restore the original repository environments and run unit tests. Ensure your current user has Docker permissions (sudo usermod -aG docker $USER).

Run the evaluation harness:

cd /data/disk2/wye/SWE-bench

1
2
3
4
5
6
7
python -m swebench.harness.run_evaluation \
--predictions_path ./predictions.jsonl \
--dataset_name princeton-nlp/SWE-bench_Lite \
--split test \
--report_dir ./eval_logs \
--max_workers 1 \
--run_id qwen_coder_test

After the evaluation finishes, you can check the detailed logs and results in the ./eval_logs directory.

Use the SWE-agent to Test

Using LLM to solve practical problem is very difficult because of lacking of context information and other problems.

Agent is good at solving problem which use LLM as “brain” and use terminal/edit tools as “limbs”.It create a docker to read code and try to solve problems.

1. Environment Preparation

First, we need the brain: SWE-agent

Then, we need a LLM to provide core think-function.

Third, we need a docker to test the real code.

End, we need a benchmark to judge the LLM’s performance.

1.1 Docker

Docker is essential for the agent to test the code.

1.2 vLLM

We can use vLLM to load a LLM directly. How ever it is probably to have a lot of tools-conflicts problem. For example, I have a server with CUDA version 13.0, while the vLLM only support version 12.4. It will cause many compile problems.

So it is recommended to use Docker to deploy vLLM and run a LLM.

The command is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
docker run -d --name vllm_server --gpus all \
-v /data/disk2/wye/models:/models \
-p 8000:8000 \
--ipc=host \
vllm/vllm-openai:latest \
--model /models/Qwen2.5-Coder-7B-Instruct \
--served-model-name qwen-local \
--dtype auto \
--max-model-len 16384 \
--gpu-memory-utilization 0.9 \
--enable-auto-tool-choice \
--tool-call-parser hermes

1.3 SWE-agent

1
cd /data/disk2/wye
1
2
conda create -n sweagent python=3.11 -y
conda activate sweagent
1
2
3
git clone https://github.com/SWE-agent/SWE-agent.git
cd SWE-agent
pip install -e .

Create a new config file for the LLM:

1
cp SWE-agent/config/cp SWE-agent/config/default.yaml qwen_local.yaml

SWE-agent version 1.x uses a strict config validation.

parse_function expects to receive a Dictionary or a specific object, rather than a plain string. It requires a format similar to {“type”: “thought_action”}.

Due to the difficulty of the 7B model in consistently producing JSON tool_call that meet OpenAI’s specifications, extracting Bash code blocks through regular expressions can significantly enhance the compatibility of smaller models.

So we need to amend the yaml file, change the parse_function from function_calling into thought_action:

1
2
parse_function:
type: thought_action

2. Run Test Command

1
cd SWE-agent
1
2
3
4
5
6
sweagent run \
--config config/qw25_7B.yaml \
--agent.model.name openai/qwen-local \
--agent.model.api_base http://localhost:8000/v1 \
--agent.model.per_instance_cost_limit 0.0 \
--problem_statement.github_url https://github.com/scikit-learn/scikit-learn/issues/25076

Analyze The Result

1. SWE-bench

1.1 astropy__astropy-12907

1.1.1 Problem Description & Input

Use the python file to extract the description of the problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import os
import json

# 【核心防卡死设置】强制使用国内镜像,并优先读取本地缓存
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
os.environ['HF_HUB_OFFLINE'] = '1' # 开启离线模式,绝对不联网

from datasets import load_dataset

print("正在从本地缓存加载 SWE-bench Lite 数据集...")
# 加载数据集
dataset = load_dataset("princeton-nlp/SWE-bench_Lite", split="test")
print(f"加载成功!共 {len(dataset)} 个任务。")

# 提取你关心的那 3 个 Astropy 任务
target_ids = ["astropy__astropy-12907", "astropy__astropy-14182", "astropy__astropy-14365"]

for item in dataset:
if item["instance_id"] in target_ids:
print(f"\n{'='*60}")
print(f"📌 任务ID: {item['instance_id']}")
print(f"📝 问题描述 (Issue 原文):\n{item['problem_statement']}")
print(f"✅ 必须修复通过的测试 (FAIL_TO_PASS):\n{item['FAIL_TO_PASS']}")
print(f"{'='*60}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
正在从本地缓存加载 SWE-bench Lite 数据集...
Using the latest cached version of the dataset since princeton-nlp/SWE-bench_Lite couldn't be found on the Hugging Face Hub (offline mode is enabled).
Found the latest cached dataset configuration 'default' at /home/ubuntu/.cache/huggingface/datasets/princeton-nlp___swe-bench_lite/default/0.0.0/6ec7bb89b9342f664a54a6e0a6ea6501d3437cc2 (last modified on Wed Jul 1 12:06:05 2026).
加载成功!共 300 个任务。

============================================================
📌 任务ID: astropy__astropy-12907
📝 问题描述 (Issue 原文):
Modeling's `separability_matrix` does not compute separability correctly for nested CompoundModels
Consider the following model:

```python
from astropy.modeling import models as m
from astropy.modeling.separable import separability_matrix

cm = m.Linear1D(10) & m.Linear1D(5)
```

It's separability matrix as you might expect is a diagonal:

```python
>>> separability_matrix(cm)
array([[ True, False],
[False, True]])
```

If I make the model more complex:
```python
>>> separability_matrix(m.Pix2Sky_TAN() & m.Linear1D(10) & m.Linear1D(5))
array([[ True, True, False, False],
[ True, True, False, False],
[False, False, True, False],
[False, False, False, True]])
```

The output matrix is again, as expected, the outputs and inputs to the linear models are separable and independent of each other.

If however, I nest these compound models:
```python
>>> separability_matrix(m.Pix2Sky_TAN() & cm)
array([[ True, True, False, False],
[ True, True, False, False],
[False, False, True, True],
[False, False, True, True]])
```
Suddenly the inputs and outputs are no longer separable?

This feels like a bug to me, but I might be missing something?

✅ 必须修复通过的测试 (FAIL_TO_PASS):
["astropy/modeling/tests/test_separable.py::test_separable[compound_model6-result6]", "astropy/modeling/tests/test_separable.py::test_separable[compound_model9-result9]"]
============================================================

============================================================
📌 任务ID: astropy__astropy-14182
📝 问题描述 (Issue 原文):
Please support header rows in RestructuredText output
### Description

It would be great if the following would work:

```Python
>>> from astropy.table import QTable
>>> import astropy.units as u
>>> import sys
>>> tbl = QTable({'wave': [350,950]*u.nm, 'response': [0.7, 1.2]*u.count})
>>> tbl.write(sys.stdout, format="ascii.rst")
===== ========
wave response
===== ========
350.0 0.7
950.0 1.2
===== ========
>>> tbl.write(sys.stdout, format="ascii.fixed_width", header_rows=["name", "unit"])
| wave | response |
| nm | ct |
| 350.0 | 0.7 |
| 950.0 | 1.2 |
>>> tbl.write(sys.stdout, format="ascii.rst", header_rows=["name", "unit"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/astropy/table/connect.py", line 129, in __call__
self.registry.write(instance, *args, **kwargs)
File "/usr/lib/python3/dist-packages/astropy/io/registry/core.py", line 369, in write
return writer(data, *args, **kwargs)
File "/usr/lib/python3/dist-packages/astropy/io/ascii/connect.py", line 26, in io_write
return write(table, filename, **kwargs)
File "/usr/lib/python3/dist-packages/astropy/io/ascii/ui.py", line 856, in write
writer = get_writer(Writer=Writer, fast_writer=fast_writer, **kwargs)
File "/usr/lib/python3/dist-packages/astropy/io/ascii/ui.py", line 800, in get_writer
writer = core._get_writer(Writer, fast_writer, **kwargs)
File "/usr/lib/python3/dist-packages/astropy/io/ascii/core.py", line 1719, in _get_writer
writer = Writer(**writer_kwargs)
TypeError: RST.__init__() got an unexpected keyword argument 'header_rows'
```


### Additional context

RestructuredText output is a great way to fill autogenerated documentation with content, so having this flexible makes the life easier `:-)`



✅ 必须修复通过的测试 (FAIL_TO_PASS):
["astropy/io/ascii/tests/test_rst.py::test_rst_with_header_rows"]
============================================================

============================================================
📌 任务ID: astropy__astropy-14365
📝 问题描述 (Issue 原文):
ascii.qdp Table format assumes QDP commands are upper case
### Description

ascii.qdp assumes that commands in a QDP file are upper case, for example, for errors they must be "READ SERR 1 2" whereas QDP itself is not case sensitive and case use "read serr 1 2".

As many QDP files are created by hand, the expectation that all commands be all-caps should be removed.

### Expected behavior

The following qdp file should read into a `Table` with errors, rather than crashing.
```
read serr 1 2
1 0.5 1 0.5
```

### How to Reproduce

Create a QDP file:
```
> cat > test.qdp
read serr 1 2
1 0.5 1 0.5
<EOF>

> python
Python 3.10.9 (main, Dec 7 2022, 02:03:23) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from astropy.table import Table
>>> Table.read('test.qdp',format='ascii.qdp')
WARNING: table_id not specified. Reading the first available table [astropy.io.ascii.qdp]
Traceback (most recent call last):
...
raise ValueError(f'Unrecognized QDP line: {line}')
ValueError: Unrecognized QDP line: read serr 1 2
```

Running "qdp test.qdp" works just fine.


### Versions

Python 3.10.9 (main, Dec 7 2022, 02:03:23) [Clang 13.0.0 (clang-1300.0.29.30)]
astropy 5.1
Numpy 1.24.1
pyerfa 2.0.0.1
Scipy 1.10.0
Matplotlib 3.6.3


✅ 必须修复通过的测试 (FAIL_TO_PASS):
["astropy/io/ascii/tests/test_qdp.py::test_roundtrip[True]"]

大模型接收到了上述 Issue 的详细文本描述(problem_statement),以及相关的代码上下文。Prompt 的核心指令是要求大模型分析这个 Bug,并直接输出修复该 Bug 的 git diff 格式的代码补丁

Todo: 看完整的 Input Prompt

1.1.2 Output & patch.diff

大模型定位到了 separability_matrix 函数中处理 CompoundModel 的递归分支。它将原本用于计算矩阵索引偏移量的代码:

1
2
i += submatrix.shape[0]
j += submatrix.shape[1]

强行修改为了

1
2
i += submatrix.shape[0] // 2
j += submatrix.shape[1] // 2

模型“猜测”嵌套模型的维度计算导致了索引翻倍或错位,于是采用了最简单粗暴的“启发式猜测”——把偏移量除以 2(整除),试图以此来“对齐”索引。

1.1.3 Evaluation

SWE-bench 的评估系统(Harness)启动了 Docker 容器,拉取了 astropy 仓库的历史代码,并尝试将大模型的补丁“打”进去。

  • 最终结果Patch Apply Failed(补丁应用失败),评估提前终止,判定为 0 分(未解决)。

  • 具体报错过程:SWE-bench 极其有耐心地尝试了三种打补丁的方式,全部失败:

    1. git apply --verbose (标准 Git 应用,失败)
    2. git apply --verbose --reject (带拒绝文件的应用,失败)
    3. patch --batch --fuzz=5 -p1 -i (允许 5 行模糊匹配的宽松模式,依然失败)
  • 失败的原因:

    1
    2
    3
    patching file astropy/modeling/separable.py
    Hunk #1 FAILED at 134.
    1 out of 1 hunk FAILED -- saving rejects to file astropy/modeling/separable.py.rej

    大模型生成的 diff 文件中,代码的缩进、空格数量或上下文行,与原始仓库中第 134 行的实际代码不匹配。Git 无法识别这段补丁应该贴在哪里,导致连代码都没改成功,更别提运行后续的 pytest 测试用例了。

这次测试非常典型地暴露了当前大模型在直接参与软件工程任务(Zero-shot 直接生成 Diff)时的两大致命缺陷

  1. 格式幻觉(最直接的死因):大模型虽然知道要输出 git diff 格式,但它无法精确控制 Python 代码中严格的空格和缩进对齐。这导致补丁在格式校验阶段就被 SWE-bench 拒收,模型连“证明自己逻辑对错”的机会都没有。
  2. 代码推理能力不足(深层原因):即使补丁成功打上,大模型给出的 // 2 这种“硬编码魔法数字”的修复方式也是完全错误的。它没有真正理解 CompoundModel 递归树展开时的维度映射数学逻辑,而是在做“文字游戏”和“数字猜测”。

2. SWE-agent

2.1