---
title: QGIS-GPT
canonical_url: "https://www.modelscope.cn/models/itpossible/QGIS-GPT"
md_url: "https://www.modelscope.cn/models/itpossible/QGIS-GPT.md"
repository: itpossible/QGIS-GPT
last_updated: 2026-06-10
pipeline_tag: text-generation
tasks:
  - text-generation
model_type:
  - qwen3
architectures:
  - Qwen3ForCausalLM
base_model_relation: finetune
parameters: 32.8B
tensor_type:
  - BF16
library_name:
  - pytorch
  - transformer
  - safetensors
frameworks:
  - Pytorch
downloads: 29
stars: 0
---

# QGIS-GPT

> QGIS-GPT - itpossible 在 ModelScope 开源的模型。本文档介绍 QGIS-GPT 模型的部署和推理方式。该模型基于 LLaMA-Factory 训练，面向 QGIS / GDAL / SAGA / GRASS 等地理处理框架的 PyQGIS 代码生成任务，可作为地理空间代码智能体的核心推理模型。

- **Repository**: itpossible/QGIS-GPT
- **Tasks**: text-generation
- **Parameters**: 32.8B
- **Downloads**: 29
- **Stars**: 0
- **Last updated**: 2026-06-10

Source: https://www.modelscope.cn/models/itpossible/QGIS-GPT

---

# QGIS-GPT 模型部署与推理说明

本文档介绍 `QGIS-GPT` 模型的部署和推理方式。该模型基于 LLaMA-Factory 训练，面向 QGIS / GDAL / SAGA / GRASS 等地理处理框架的 PyQGIS 代码生成任务，可作为地理空间代码智能体的核心推理模型。

## 模型简介

QGIS-GPT 以 Qwen3-32B 为基础模型，采用 LoRA 参数高效微调方式训练，重点提升模型对标准化地理处理算子接口、参数约束和执行逻辑的理解能力。模型训练数据包含算法理解任务和 PyQGIS 代码生成任务，其中代码样本经过沙箱执行验证，以降低通用大模型在地理空间代码生成中的幻觉问题。

模型训练采用三阶段阶梯式对齐策略：

1. **Stage 1：持续预训练与权重分布对齐**  
   使用通用语料构造平滑的领域迁移过渡区，降低灾难性遗忘风险。

2. **Stage 2：渐进式地学知识对齐**  
   混合地学语料、GIS 文档和通用语料，提升模型对地学术语和专业语义的理解能力。

3. **Stage 3：契约感知指令微调**  
   基于自动构造并经过质量过滤的指令数据进行微调，使模型学习 QGIS 标准处理框架中的算法 ID、参数约束和代码组织方式。

## 下载方法
SDK下载
```bash
#安装ModelScope
pip install modelscope
```
```python
#SDK模型下载
from modelscope import snapshot_download
model_dir = snapshot_download('itpossible/QGIS-GPT')
```

## 部署环境

建议使用 Python 3.10+，并安装以下依赖：

```bash
pip install -U "transformers>=4.55.0" accelerate torch safetensors
pip install -U vllm
```

如果需要在 QGIS Python 环境中执行模型生成的代码，还需要确保本机已安装 QGIS，并可在 QGIS Python 控制台或独立 PyQGIS 环境中导入：

```python
from qgis.core import QgsProject
import processing
```

## 使用 Transformers 进行本地推理

适合单机调试、离线推理和少量样本测试。

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_path = "itpossible/QGIS-GPT"

tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)

messages = [
    {
        "role": "user",
        "content": "Calculate the aspect from this coastal DEM raster file. The data path is D:/AutoGIS/sample_data/raster/dem/dem_coastal.tif",
    },
]

text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
    enable_thinking=False,
)

inputs = tokenizer([text], return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model.generate(
        **inputs,
        max_new_tokens=2048,
        temperature=0.6,
        top_p=0.95,
        top_k=20,
        do_sample=True,
        eos_token_id=tokenizer.eos_token_id,
    )

generated_ids = outputs[0][inputs.input_ids.shape[-1]:]
response = tokenizer.decode(generated_ids, skip_special_tokens=True)
print(response)
```

### Transformers 推理建议
- 对代码生成任务，建议设置较长的 `max_new_tokens`，例如 `4096`。
- 若希望输出更稳定，可降低 `temperature`，例如设置为 `0.1` 到 `0.4`。

## 使用 vLLM 部署 OpenAI 兼容服务

vLLM 适合高吞吐推理、服务化部署和与代码智能体集成。以下示例将模型部署为 OpenAI Chat Completions 兼容接口。

```bash
vllm serve /itpossible/QGIS-GPT \
  --host 0.0.0.0 \
  --port 8000 \
  --served-model-name qgis-gpt \
  --tensor-parallel-size 2 \
  --dtype bfloat16 \
  --max-model-len 12000 \
  --gpu-memory-utilization 0.90
```

如果只有单张 GPU，可将 `--tensor-parallel-size` 改为 `1`。如果显存不足，可适当降低 `--max-model-len`，例如改为 `8192` 或 `10000`。

### vLLM Python 客户端调用

```python
from openai import OpenAI

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

response = client.chat.completions.create(
    model="qgis-gpt",
    messages=[
        {
            "role": "user",
            "content": "Calculate the aspect from this coastal DEM raster file. The data path is D:/AutoGIS/sample_data/raster/dem/dem_coastal.tif",
        },
    ],
    temperature=0.6,
    top_p=0.95,
    max_tokens=2048,
)

print(response.choices[0].message.content)
```

### vLLM curl 调用

```bash
curl http://127.0.0.1:8104/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qgis-gpt",
    "messages": [
      {
        "role": "user",
        "content": "Calculate the aspect from this coastal DEM raster file. The data path is D:/AutoGIS/sample_data/raster/dem/dem_coastal.tif"
      }
    ],
    "temperature": 0.6,
    "top_p": 0.95,
    "max_tokens": 2048
  }'
```

## 推理提示词建议

为了获得更稳定、可执行的 PyQGIS 代码，建议在 system prompt 中明确以下要求：

```text
You are QGIS-GPT, an expert model for generating executable PyQGIS code.
Generate complete Python code for QGIS Processing tasks.
Use correct QGIS, GDAL, SAGA, or GRASS algorithm IDs and parameters.
Create output directories when necessary.
Load generated outputs back into the QGIS project when appropriate.
```

## 使用 Case

以下表格展示了两个 PyQGIS 代码生成使用示例，完整 Answer 见各 Case 下方代码块。

| Case | Query |
| --- | --- |
| Case 1 | Calculate the aspect from this coastal DEM raster file. The data path is D:/AutoGIS/sample_data/raster/dem/dem_coastal.tif |
| Case 2 | Create a 0.5 degree buffer around all Chinese cities in my dataset. The data path is D:/AutoGIS/sample_data/vector/points/china_cities.geojson |

### Case 1 Answer

```python

from qgis.core import QgsRasterLayer, QgsProject
import processing
import os

# Define input raster path
input_dem = "D:/AutoGIS/sample_data/raster/dem/dem_coastal.tif"

# Define output path for aspect result
output_dir = "D:/AutoGIS/sample_data/raster/dem"
output_aspect = os.path.join(output_dir, "dem_coastal_aspect.tif")

# Load the input DEM raster layer
dem_layer = QgsRasterLayer(input_dem, "DEM Coastal")

# Check if the layer is valid
if not dem_layer.isValid():
    print("Error: Failed to load the DEM layer!")
else:
    print("DEM layer loaded successfully.")
    
    # Run the GDAL aspect algorithm
    result = processing.run('gdal:aspect', {
        'INPUT': input_dem,
        'BAND': 1,
        'TRIG_ANGLE': False,  # Use azimuth (not trigonometric angle)
        'ZERO_FLAT': True,    # Return 0 for flat areas instead of -9999
        'COMPUTE_EDGES': True,  # Compute edges for better results
        'ZEVENBERGEN': False,  # Use Horn's formula (default)
        'CREATION_OPTIONS': '',
        'EXTRA': '',
        'OUTPUT': output_aspect
    })
    
    # Load the output aspect layer into QGIS
    aspect_layer = QgsRasterLayer(result['OUTPUT'], "Aspect - Coastal DEM")
    
    if aspect_layer.isValid():
        QgsProject.instance().addMapLayer(aspect_layer)
        print("Aspect calculation completed successfully!")
        print(f"Output saved to: {output_aspect}")
    else:
        print("Error: Failed to load the aspect result layer.")
```

### Case 2 Answer

```python
from qgis.core import QgsVectorLayer, QgsProject
import processing
import os

# Define input file path
input_path = "D:/AutoGIS/sample_data/vector/points/china_cities.geojson"

# Load the input vector layer
input_layer = QgsVectorLayer(input_path, "China Cities", "ogr")

# Check if layer is valid
if not input_layer.isValid():
    print("Failed to load the input layer!")
else:
    print("Input layer loaded successfully!")
    
    # Define output path for the buffered result
    output_dir = "D:/AutoGIS/sample_data/vector/output"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    output_path = os.path.join(output_dir, "china_cities_buffered.geojson")
    
    # Run the GRASS v.buffer algorithm
    # Buffer distance is specified in degrees (map units) for lat/lon data
    result = processing.run('grass:v.buffer', {
        'input': input_layer,
        'cats': '',
        'where': '',
        'type': [0],  # 0 = point
        'distance': 0.5,  # Buffer distance in degrees (approximately 55 km at equator)
        'minordistance': None,
        'angle': 0,
        'layer': '-1',  # All layers
        'column': None,
        'scale': 1.0,
        'tolerance': 0.01,
        '-s': False,  # Do not make outside corners straight
        '-c': False,  # Make caps at ends
        '-t': True,   # Transfer categories and attributes
        'output': output_path,
        'GRASS_REGION_PARAMETER': None,
        'GRASS_SNAP_TOLERANCE_PARAMETER': -1,
        'GRASS_MIN_AREA_PARAMETER': 0.0001,
        'GRASS_OUTPUT_TYPE_PARAMETER': 3,  # area output
        'GRASS_VECTOR_DSCO': '',
        'GRASS_VECTOR_LCO': '',
        'GRASS_VECTOR_EXPORT_NOCAT': False
    })
    
    # Load the buffered result into QGIS
    buffered_layer = QgsVectorLayer(result['output'], "China Cities Buffered (0.5deg)", "ogr")
    
    if buffered_layer.isValid():
        QgsProject.instance().addMapLayer(buffered_layer)
        print(f"Buffer operation completed successfully!")
        print(f"Output saved to: {output_path}")
    else:
        print("Failed to load the buffered layer!")
```

## 注意事项

- 模型输出的是 PyQGIS 代码，代码执行依赖本地 QGIS、Processing 插件和相关 Provider，例如 GDAL、GRASS、SAGA。
- 在独立 Python 环境执行 PyQGIS 代码时，需要正确配置 `QGIS_PREFIX_PATH`、`PYTHONPATH` 和相关动态库路径。
- 建议先在 QGIS Python 控制台中验证生成代码，再集成到自动化执行环境。
