Commit 037608eb authored by chenych's avatar chenych
Browse files

First commit

parent 85fd818e
# Contributors
None
\ No newline at end of file
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 GLM-4-9B Model Team @ Zhipu AI
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# GLM-4.2V
# GLM-4.1V
## 论文
`GLM-4.1V-Thinking: Towards Versatile Multimodal Reasoning with Scalable Reinforcement Learning`
- https://arxiv.org/abs/2507.01006
## 模型结构
GLM-4.1V-Thinking 有三部分组成:
1. 一个视觉 Transformer 编码器,用于处理和编码图像及视频;
2. 一个多层感知机投影器,用于将视觉特征与标记对齐;
3. 一个大型语言模型作为语言解码器,用于处理多模态标记并生成标记补全内容。
<div align=center>
<img src="./doc/model.png"/>
</div>
## 算法原理
GLM-4.1V-thinging旨在探索视觉语言模型推理能力的上限,通过引入“思考范式”并利用采样强化学习 RLCS(Reinforcement Learning with Curriculum Sampling)全面提升模型能力。在 100 亿参数的视觉语言模型中,其性能处于领先地位,在 18 项基准测试任务中与 720 亿参数的 Qwen-2.5-VL-72B 相当甚至更优。
GLM-4.1V-Thinking能够将图像和视频以其原始的分辨率和宽高比进行识别。对于视频输入,会在每帧后面插入额外的时间索引标记,以增强模型的时间理解能力。
与上一代的 CogVLM2 及 GLM-4V 系列模型相比,**GLM-4.1V-Thinking** 有如下改进:
1. 系列中首个推理模型,不仅仅停留在数学领域,在多个子领域均达到世界前列的水平。
2. 支持 **64k** 上下长度。
3. 支持**任意长宽比**和高达 **4k** 的图像分辨率。
4. 提供支持**中英文双语**的开源模型版本。
<div align=center>
<img src="./doc/methods.png"/>
</div>
## 环境配置
### 硬件需求
DCU型号:K100_AI,节点数量:1台,卡数:1张。
`-v 路径``docker_name``imageID`根据实际情况修改
### Docker(方法一)
```
docker pull image.sourcefind.cn:5000/dcu/admin/base/vllm:0.8.5-ubuntu22.04-dtk25.04.1-rc5-das1.6-py3.10-20250711
docker run -it --shm-size 200g --network=host --name {docker_name} --privileged --device=/dev/kfd --device=/dev/dri --device=/dev/mkfd --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -u root -v /path/your_code_data/:/path/your_code_data/ -v /opt/hyhal/:/opt/hyhal/:ro {imageID} bash
cd /your_code_path/glm-4.1v_pytorch
pip install transformers==4.53.2
```
### Dockerfile(方法二)
此处提供dockerfile的使用方法
```
docker build --no-cache -t glm-4.1v:latest .
docker run -it --shm-size 200g --network=host --name {docker_name} --privileged --device=/dev/kfd --device=/dev/dri --device=/dev/mkfd --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -u root -v /path/your_code_data/:/path/your_code_data/ -v /opt/hyhal/:/opt/hyhal/:ro {imageID} bash
cd /your_code_path/glm-4.1v_pytorch
pip install transformers==4.53.2
```
### Anaconda(方法三)
此处提供本地配置、编译的详细步骤,例如:
关于本项目DCU显卡所需的特殊深度学习库可从[光合](https://developer.sourcefind.cn/tool/)开发者社区下载安装。
```
DTK驱动:dtk25.04.1
python:python3.10
torch: 2.4.1+das.opt1.dtk25041
```
`Tips:以上dtk驱动、python、torch等DCU相关工具版本需要严格一一对应`
其它非深度学习库参照requirements.txt安装:
```
pip install transformers==4.53.2
```
## 数据集
[LLaMA-Factory](https://developer.sourcefind.cn/codes/OpenDAS/llama-factory)已经支持本模型的微调。以下是构建数据集的说明,这是一个使用了两张图片的数据集。你需要将数据集整理为`finetune.json`,然后根据llama-factory中的数据配置进行相关修改。
```json
[
{
"messages": [
{
"content": "<image>Who are they?",
"role": "user"
},
{
"content": "<think>\nUser ask me to observe the image and get the answer. I Know they are Kane and Gretzka from Bayern Munich.</think>\n<answer>They're Kane and Gretzka from Bayern Munich.</answer>",
"role": "assistant"
},
{
"content": "<image>What are they doing?",
"role": "user"
},
{
"content": "<think>\nI need to observe what this people are doing. Oh, They are celebrating on the soccer field.</think>\n<answer>They are celebrating on the soccer field.</answer>",
"role": "assistant"
}
],
"images": [
"mllm_demo_data/1.jpg",
"mllm_demo_data/2.jpg"
]
}
]
```
1. `<think> XXX </think>` 中的部分不会被存放为历史记录和微调。
2. `<image>` 标签会被替换成图片信息。
## 训练
### Llama Factory 微调方法(推荐)
因为transformers版本与[LLaMA-Factory](https://developer.sourcefind.cn/codes/OpenDAS/llama-factory)版本不一致, 启动训练前需要先增加环境变量来跳过版本检查,环境变量如下:
```
export DISABLE_VERSION_CHECK=1
```
#### 全参微调
SFT训练脚本示例,参考`llama-factory/train_full`下对应yaml文件。
**参数修改**
- **--model_name_or_path**: 修改为待训练模型地址,如 `/data/GLM-4.1V-9B-Thinking`
- **--dataset**: 微调训练集名称,可选数据集请参考 `llama-factory/data/dataset_info.json`
- **--template**: 将 default 修改为 `glm4v`
- **--output_dir**: 模型保存地址
其他参数如:`--learning_rate``--save_steps`可根据自身硬件及需求进行修改。
#### lora微调
SFT训练脚本示例,参考`llama-factory/train_lora`下对应yaml文件。
参数解释同[#全参微调](#全参微调)
## 推理
- `trans_infer_transformers.py`: 使用`transformers`库进行单次对话推理。
- `trans_infer_cli.py`: 使用`transformers`库作为推理后端的命令行交互脚本。你可以使用它进行连续对话。
```
# 单次推理启动命令如下
python inference/trans_infer_transformers.py
# 交互对话启动命令如下:
python inference/trans_infer_cli.py
```
## result
<div align=center>
<img src="./doc/results-dcu.png"/>
</div>
### 精度
测试数据:[test data](https://developer.sourcefind.cn/codes/OpenDAS/llama-factory/-/blob/master/data/alpaca_en_demo.json),使用的加速卡:K100_AI。
模型:GLM-4.1V-9B-Thinking
| device | iters | train_loss |
| :------: | :------: | :------: |
| A800 | 375 | |
| K100_AI | 375 | 0.5264 |
## 应用场景
### 算法类别
`对话问答`
### 热点应用行业
`制造,广媒,家居,教育`
## 预训练权重
- [GLM-4.1V-9B-Base](https://huggingface.co/THUDM/GLM-4.1V-9B-Base)
- [GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking)
## 源码仓库及问题反馈
- https://developer.sourcefind.cn/codes/modelzoo/glm-4.1v_pytorch
## 参考资料
- https://github.com/THUDM/GLM-4.1V-Thinking
# GLM-4.1V-Thinking
[中文阅读](./README_zh.md)
<div align="center">
<img src=resources/logo.svg width="40%"/>
</div>
<p align="center">
👋 Join our <a href="resources/WECHAT.md" target="_blank">Wechat</a> or <a href="https://discord.com/invite/8cnQKdAprg" target="_blank">Discord</a>
<br>
📖 View the GLM-4.1V-9B-Thinking <a href="https://arxiv.org/abs/2507.01006" target="_blank">paper</a>.
<br>
💡 Try the <a href="https://huggingface.co/spaces/THUDM/GLM-4.1V-9B-Thinking-API-Demo" target="_blank">Hugging Face</a> or <a href="https://modelscope.cn/studios/ZhipuAI/GLM-4.1V-9B-Thinking-Demo" target="_blank">ModelScope</a> online demo for GLM-4.1V-9B-Thinking.
<br>
📍 Using GLM-4.1V-9B-Thinking API at <a href="https://www.bigmodel.cn/dev/api/visual-reasoning-model/GLM-4.1V-Thinking">Zhipu Foundation Model Open Platform</a>
</p>
## Project Updates
- 🔥 **News**: `2025/07/16`: We have open-sourced the **VLM Reward System** used in training GLM-4.1V-Thinking! Check out the [repo here](https://github.com/THUDM/GLM-4.1V-Thinking/tree/main/glmv_reward) and try it locally: `python examples/reward_system_demo.py`
- **News**: `2025/07/02`: The [GLM-4.1V-9B-Thinking series](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking) is now open-sourced! Supports enhanced visual reasoning and agent interaction.
- **News**: `2025/07/01`: We released the [Technical Report](https://arxiv.org/abs/2507.01006) for GLM-4.1V-Thinking.
## Model Introduction
Vision-Language Models (VLMs) have become foundational components of intelligent systems. As real-world AI tasks grow
increasingly complex, VLMs must evolve beyond basic multimodal perception to enhance their reasoning capabilities in
complex tasks. This involves improving accuracy, comprehensiveness, and intelligence, enabling applications such as
complex problem solving, long-context understanding, and multimodal agents.
Based on the [GLM-4-9B-0414](https://github.com/THUDM/GLM-4) foundation model, we present the new open-source VLM model
**GLM-4.1V-9B-Thinking**, designed to explore the upper limits of reasoning in vision-language models. By introducing
a "thinking paradigm" and leveraging reinforcement learning, the model significantly enhances its capabilities. It
achieves state-of-the-art performance among 10B-parameter VLMs, matching or even surpassing the 72B-parameter
Qwen-2.5-VL-72B on 18 benchmark tasks. We are also open-sourcing the base model GLM-4.1V-9B-Base to
support further research into the boundaries of VLM capabilities.
![rl](resources/rl.jpeg)
Compared to the previous generation models CogVLM2 and the GLM-4V series, **GLM-4.1V-Thinking** offers the
following improvements:
1. The first reasoning-focused model in the series, achieving world-leading performance not only in mathematics but also
across various sub-domains.
2. Supports **64k** context length.
3. Handles **arbitrary aspect ratios** and up to **4K** image resolution.
4. Provides an open-source version supporting both **Chinese and English bilingual** usage.
## Model Information
### Model Download Links
| Model | Download Links | Model Type |
|----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|-----------------|
| GLM-4.1V-9B-Thinking | [🤗 Hugging Face](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-4.1V-9B-Thinking) | Reasoning Model |
| GLM-4.1V-9B-Base | [🤗 Hugging Face](https://huggingface.co/THUDM/GLM-4.1V-9B-Base)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-4.1V-9B-Base) | Base Model |
The model's algorithm implementation can be found in the
official [transformers](https://github.com/huggingface/transformers/tree/main/src/transformers/models/glm4v) repository.
### Runtime Requirements
#### Inference
| Device (Single GPU) | Framework | Min Memory | Speed | Precision |
|---------------------|--------------|------------|--------------------|-----------|
| NVIDIA A100 | transformers | 22GB | 14 - 22 Tokens / s | BF16 |
| NVIDIA A100 | vLLM | 22GB | 60 - 70 Tokens / s | BF16 |
#### Fine-tuning
The following results are based on image fine-tuning using the [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory)
toolkit.
| Device (Cluster) | Strategy | Min Memory / # of GPUs | Batch Size (per GPU) | Freezing |
|------------------|------------|------------------------|----------------------|-------------|
| NVIDIA A100 | LORA | 21GB / 1 GPU | 1 | Freeze VIT |
| NVIDIA A100 | FULL ZERO2 | 280GB / 4 GPUs | 1 | Freeze VIT |
| NVIDIA A100 | FULL ZERO3 | 192GB / 4 GPUs | 1 | Freeze VIT |
| NVIDIA A100 | FULL ZERO2 | 304GB / 4 GPUs | 1 | No Freezing |
| NVIDIA A100 | FULL ZERO3 | 210GB / 4 GPUs | 1 | No Freezing |
> Note: Fine-tuning with Zero2 may result in zero loss; Zero3 is recommended for stable training.
## Benchmark Performance
Based on the [GLM-4-9B-0414](https://github.com/THUDM/GLM-4) foundation model, we present the new open-source VLM model
**GLM-4.1V-9B-Thinking**, which introduces a "thinking" paradigm and leverages Reinforcement Learning with Curriculum
Sampling (RLCS) to comprehensively enhance model capabilities.
It achieves state-of-the-art performance among vision-language models at the 10B parameter scale, matching or even
surpassing the 72B Qwen-2.5-VL on 18 benchmark tasks.
We also open-source the base model **GLM-4.1V-9B-Base** to support further research on the frontier of vision-language
models.
![bench](resources/bench.jpeg)
## Model Inference
All inference scripts are located in the `inference` folder and include:
- `trans_infer_cli.py`: A command-line interactive script using the `transformers` library as the backend. It supports
multi-turn dialogue.
- `trans_infer_gradio.py`: A Gradio-based web UI script using the `transformers` backend. It supports multimodal inputs
such as images, videos, PDFs, and PPTs.
- OpenAI-compatible API service with `vllm`, along with a simple request example provided in `vllm_api_request.py`.
```shell
vllm serve THUDM/GLM-4.1V-9B-Thinking --limit-mm-per-prompt '{"image":32}' --allowed-local-media-path /
```
- If `--limit-mm-per-prompt` is not specified, only 1 image is supported. The model supports a maximum of 1 video or
300 images per input — it does **not** support simultaneous image and video inputs.
- `--allowed-local-media-path` must be set to permit access to local multimodal inputs.
- `trans_infer_bench`: Academic benchmarking script for inference with `GLM-4.1V-9B-Thinking`. Key features:
- Automatically interrupts thinking if it exceeds 8192 tokens and appends `</think><answer>` to prompt the model to
generate a final answer.
- Demonstrates video-based input; for other modalities, modifications are required.
- Only a `transformers` version is provided. For `vLLM`, a custom implementation is needed to support this logic.
- `vllm_request_gui_agent.py`: This script demonstrates how to handle model responses and construct prompts for GUI
Agent use cases. It covers strategies for mobile, desktop, and web environments, and can be integrated into your
application framework. For detailed documentation about GUI Agent, please refer to [this file](resources/agent.md).
- For Ascend NPU Inference, Check [here](https://gitee.com/ascend/MindSpeed-MM/tree/master/examples/glm4.1v/README.md).
## Model Fine-tuning
[LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory) now supports fine-tuning of this model. Below is an example
dataset using two images. Prepare your dataset in a `finetune.json` file like the following:
```json
[
{
"messages": [
{
"content": "<image>Who are they?",
"role": "user"
},
{
"content": "<think>\nUser ask me to observe the image and get the answer. I Know they are Kane and Gretzka from Bayern Munich.</think>\n<answer>They're Kane and Gretzka from Bayern Munich.</answer>",
"role": "assistant"
},
{
"content": "<image>What are they doing?",
"role": "user"
},
{
"content": "<think>\nI need to observe what this people are doing. Oh, They are celebrating on the soccer field.</think>\n<answer>They are celebrating on the soccer field.</answer>",
"role": "assistant"
}
],
"images": [
"mllm_demo_data/1.jpg",
"mllm_demo_data/2.jpg"
]
}
]
```
1. Content inside `<think> ... </think>` will **not** be stored in the conversation history or used during fine-tuning.
2. The `<image>` tag will be replaced with actual image data during preprocessing.
After preparing the dataset, you can proceed with fine-tuning using the standard LLaMA-Factory pipeline.
## Model License
- The code in this repository is released under the [Apache License 2.0](LICENSE).
- The models **GLM-4.1V-9B-Thinking** and **GLM-4.1V-9B-Base** are both licensed under the **MIT License**.
## Citation
If you find our work helpful, please consider citing the following paper.
```bibtex
@misc{glmvteam2025glm41vthinkingversatilemultimodalreasoning,
title={GLM-4.1V-Thinking: Towards Versatile Multimodal Reasoning with Scalable Reinforcement Learning},
author={GLM-V Team and Wenyi Hong and Wenmeng Yu and Xiaotao Gu and Guo Wang and Guobing Gan and Haomiao Tang and Jiale Cheng and Ji Qi and Junhui Ji and Lihang Pan and Shuaiqi Duan and Weihan Wang and Yan Wang and Yean Cheng and Zehai He and Zhe Su and Zhen Yang and Ziyang Pan and Aohan Zeng and Baoxu Wang and Boyan Shi and Changyu Pang and Chenhui Zhang and Da Yin and Fan Yang and Guoqing Chen and Jiazheng Xu and Jiali Chen and Jing Chen and Jinhao Chen and Jinghao Lin and Jinjiang Wang and Junjie Chen and Leqi Lei and Letian Gong and Leyi Pan and Mingzhi Zhang and Qinkai Zheng and Sheng Yang and Shi Zhong and Shiyu Huang and Shuyuan Zhao and Siyan Xue and Shangqin Tu and Shengbiao Meng and Tianshu Zhang and Tianwei Luo and Tianxiang Hao and Wenkai Li and Wei Jia and Xin Lyu and Xuancheng Huang and Yanling Wang and Yadong Xue and Yanfeng Wang and Yifan An and Yifan Du and Yiming Shi and Yiheng Huang and Yilin Niu and Yuan Wang and Yuanchang Yue and Yuchen Li and Yutao Zhang and Yuxuan Zhang and Zhanxiao Du and Zhenyu Hou and Zhao Xue and Zhengxiao Du and Zihan Wang and Peng Zhang and Debing Liu and Bin Xu and Juanzi Li and Minlie Huang and Yuxiao Dong and Jie Tang},
year={2025},
eprint={2507.01006},
archivePrefix={arXiv},
primaryClass={cs.CV},
url={https://arxiv.org/abs/2507.01006},
}
```
FROM image.sourcefind.cn:5000/dcu/admin/base/vllm:0.8.5-ubuntu22.04-dtk25.04.1-rc5-das1.6-py3.10-20250711
\ No newline at end of file
icon.png

53.8 KB

"""
A command-line interface for chatting with GLM-4.1V-9B-Thinkng model supporting images and videos.
Examples:
# Text-only chat
python trans_infer_cli.py
# Chat with single image
python trans_infer_cli.py --image_paths /path/to/image.jpg
# Chat with multiple images
python trans_infer_cli.py --image_paths /path/to/img1.jpg /path/to/img2.png /path/to/img3.png
# Chat with single video
python trans_infer_cli.py --video_path /path/to/video.mp4
# Custom generation parameters
python trans_infer_cli.py --temperature 0.8 --top_k 5 --max_tokens 4096
Notes:
- Media files are loaded once at startup and persist throughout the conversation
- Type 'exit' to quit the chat
- Chat with images and video is NOT allowed
- The model will remember the conversation history and can reference uploaded media in subsequent turns
"""
import argparse
import re
import torch
from transformers import AutoProcessor, Glm4vForConditionalGeneration
def build_content(image_paths, video_path, text):
content = []
if image_paths:
for img_path in image_paths:
content.append({"type": "image", "url": img_path})
if video_path:
content.append({"type": "video", "url": video_path})
content.append({"type": "text", "text": text})
return content
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model_path", type=str, default="THUDM/GLM-4.1V-9B-Thinking")
parser.add_argument("--image_paths", type=str, nargs="*", default=None)
parser.add_argument("--video_path", type=str, default=None)
parser.add_argument("--max_tokens", type=int, default=8192)
parser.add_argument("--temperature", type=float, default=1.0)
parser.add_argument("--repetition_penalty", type=float, default=1.0)
parser.add_argument("--top_k", type=int, default=2)
args = parser.parse_args()
processor = AutoProcessor.from_pretrained(args.model_path, use_fast=True)
model = Glm4vForConditionalGeneration.from_pretrained(
args.model_path, torch_dtype=torch.bfloat16, device_map="cuda:0"
)
messages = []
first_turn = True
if args.image_paths is not None and args.video_path is not None:
raise ValueError(
"Chat with images and video is NOT allowed. Please use either --image_paths or --video_path, not both."
)
while True:
question = input("\nUser: ").strip()
if question.lower() == "exit":
break
if first_turn:
content = build_content(args.image_paths, args.video_path, question)
first_turn = False
else:
content = [{"type": "text", "text": question}]
messages.append({"role": "user", "content": content})
inputs = processor.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_dict=True,
return_tensors="pt",
padding=True,
).to(model.device)
output = model.generate(
**inputs,
max_new_tokens=args.max_tokens,
repetition_penalty=args.repetition_penalty,
do_sample=args.temperature > 0,
top_k=args.top_k,
temperature=args.temperature if args.temperature > 0 else None,
)
raw = processor.decode(
output[0][inputs["input_ids"].shape[1] : -1], skip_special_tokens=False
)
match = re.search(r"<answer>(.*?)</answer>", raw, re.DOTALL)
answer = match.group(1).strip() if match else ""
messages.append(
{"role": "assistant", "content": [{"type": "text", "text": answer}]}
)
print(f"Assistant: {raw}")
if __name__ == "__main__":
main()
from transformers import AutoProcessor, Glm4vForConditionalGeneration
import torch
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--model_path", type=str, default="THUDM/GLM-4.1V-9B-Thinking", help="Path to the model")
args = parser.parse_args()
if __name__ == "__main__":
# Example usage
messages = [
{
"role": "user",
"content": [
{
"type": "image",
"url": "doc/Grayscale_8bits_palette_sample_image.png"
},
{
"type": "text",
"text": "describe this image"
}
],
}
]
# Load model and processor
processor = AutoProcessor.from_pretrained(args.model_path, use_fast=True)
model = Glm4vForConditionalGeneration.from_pretrained(
pretrained_model_name_or_path=args.model_path,
torch_dtype=torch.bfloat16,
device_map="auto",
)
# process inputs
inputs = processor.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_dict=True,
return_tensors="pt"
).to(model.device)
# generate
generated_ids = model.generate(**inputs, max_new_tokens=8192)
output_text = processor.decode(generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=False)
print("output:\n", output_text)
### model
model_name_or_path: THUDM/GLM-4.1V-9B-Thinking
trust_remote_code: true
### method
stage: sft
do_train: true
finetuning_type: full
deepspeed: examples/deepspeed/ds_z3_config.json # choices: [ds_z0_config.json, ds_z2_config.json, ds_z3_config.json]
### dataset
dataset: alpaca_en_demo
template: glm4v
cutoff_len: 2048
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16
dataloader_num_workers: 4
### output
output_dir: saves/glm-4.1v-9b-thinking/full/sft
logging_steps: 1
save_steps: 500
plot_loss: true
overwrite_output_dir: true
save_only_model: false
report_to: none # choices: [none, wandb, tensorboard, swanlab, mlflow]
### train
per_device_train_batch_size: 1
gradient_accumulation_steps: 2
learning_rate: 1.0e-5
num_train_epochs: 3.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true
ddp_timeout: 180000000
resume_from_checkpoint: null
### eval
# eval_dataset: alpaca_en_demo
# val_size: 0.1
# per_device_eval_batch_size: 1
# eval_strategy: steps
# eval_steps: 500
### model
model_name_or_path: THUDM/GLM-4.1V-9B-Thinking
trust_remote_code: true
### method
stage: sft
do_train: true
finetuning_type: lora
lora_rank: 8
lora_target: all
deepspeed: examples/deepspeed/ds_z3_config.json # choices: [ds_z0_config.json, ds_z2_config.json, ds_z3_config.json]
### dataset
dataset: alpaca_en_demo
template: glm4v
cutoff_len: 2048
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16
dataloader_num_workers: 4
### output
output_dir: saves/glm-4.1v-9b-thinking/lora/sft
logging_steps: 10
save_steps: 500
plot_loss: true
overwrite_output_dir: true
save_only_model: false
report_to: none # choices: [none, wandb, tensorboard, swanlab, mlflow]
### train
per_device_train_batch_size: 1
gradient_accumulation_steps: 2
learning_rate: 1.0e-4
num_train_epochs: 3.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true
ddp_timeout: 180000000
resume_from_checkpoint: null
### eval
# eval_dataset: alpaca_en_demo
# val_size: 0.1
# per_device_eval_batch_size: 1
# eval_strategy: steps
# eval_steps: 500
# 模型唯一标识
modelCode=1668
# 模型名称
modelName=GLM-4.1V_pytorch
# 模型描述
modelDescription=GLM-4.1V-9B-Thinking 通过引入「思维链」(Chain-of-Thought)推理机制,在回答准确性、内容丰富度与可解释性方面,全面超越传统的非推理式视觉模型。
# 应用场景
appScenario=推理,训练,对话问答,制造,广媒,家居,教育
# 框架类型
frameType=pytorch
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment