syjarvis commited on
Commit
138ef79
·
verified ·
1 Parent(s): 3e88652

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +144 -121
README.md CHANGED
@@ -1,199 +1,222 @@
1
  ---
2
- library_name: transformers
3
- tags: []
 
4
  ---
5
 
6
- # Model Card for Model ID
7
 
8
- <!-- Provide a quick summary of what the model is/does. -->
9
 
 
10
 
 
11
 
12
- ## Model Details
13
 
14
- ### Model Description
15
 
16
- <!-- Provide a longer summary of what this model is. -->
17
 
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
 
 
 
 
 
19
 
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
 
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
 
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
 
70
- ## How to Get Started with the Model
 
 
 
 
 
 
 
71
 
72
- Use the code below to get started with the model.
73
 
74
- [More Information Needed]
75
 
76
- ## Training Details
77
 
78
- ### Training Data
79
 
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
 
 
 
 
81
 
82
- [More Information Needed]
83
 
84
- ### Training Procedure
 
 
85
 
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
 
88
- #### Preprocessing [optional]
89
 
90
- [More Information Needed]
91
 
 
92
 
93
- #### Training Hyperparameters
94
 
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
 
97
- #### Speeds, Sizes, Times [optional]
 
 
 
98
 
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
 
101
- [More Information Needed]
 
 
102
 
103
- ## Evaluation
104
 
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
 
107
- ### Testing Data, Factors & Metrics
 
 
108
 
109
- #### Testing Data
110
 
111
- <!-- This should link to a Dataset Card if possible. -->
 
 
112
 
113
- [More Information Needed]
114
 
115
- #### Factors
116
 
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
 
119
- [More Information Needed]
120
 
121
- #### Metrics
 
 
 
 
122
 
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
 
125
- [More Information Needed]
 
 
126
 
127
- ### Results
 
 
128
 
129
- [More Information Needed]
 
130
 
131
- #### Summary
 
 
132
 
 
133
 
 
 
 
 
 
134
 
135
- ## Model Examination [optional]
 
 
 
136
 
137
- <!-- Relevant interpretability work for the model goes here -->
 
 
 
138
 
139
- [More Information Needed]
 
 
 
 
 
 
 
140
 
141
- ## Environmental Impact
 
 
142
 
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
 
 
 
 
 
 
144
 
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
 
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
 
153
- ## Technical Specifications [optional]
 
 
 
 
 
154
 
155
- ### Model Architecture and Objective
156
 
157
- [More Information Needed]
158
 
159
- ### Compute Infrastructure
160
 
161
- [More Information Needed]
162
 
163
- #### Hardware
164
 
165
- [More Information Needed]
 
 
166
 
167
- #### Software
168
 
169
- [More Information Needed]
170
 
171
- ## Citation [optional]
172
 
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
 
 
 
 
 
174
 
175
- **BibTeX:**
176
 
177
- [More Information Needed]
178
 
179
- **APA:**
180
 
181
- [More Information Needed]
 
 
182
 
183
- ## Glossary [optional]
184
 
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
 
187
- [More Information Needed]
188
 
189
- ## More Information [optional]
190
 
191
- [More Information Needed]
192
 
193
- ## Model Card Authors [optional]
194
 
195
- [More Information Needed]
196
 
197
- ## Model Card Contact
198
 
199
- [More Information Needed]
 
 
 
1
  ---
2
+ language:
3
+ - zh
4
+ license: apache-2.0
5
  ---
6
 
7
+ <div align="center">
8
 
9
+ ![logo](./images/logb.png)
10
 
11
+ # mini-embed-vision
12
 
13
+ 轻量级中文图文统一嵌入模型(Multimodal Embedding Model for Chinese)
14
 
15
+ 中文 | [English](./README_en.md)
16
 
17
+ </div>
18
 
19
+ ## 📌 简介
20
 
21
+ * **mini-embed-vision** 是一个轻量级的中文多模态嵌入模型,旨在为个人开发者提供可复现、低成本、高性能的图文联合嵌入方案。
22
+ * 本项目在 **冻结文本编码器** 的前提下,基于对比学习(Contrastive Learning)框架,通过可训练的投影层对齐图像与文本的嵌入空间,在显著降低训练成本的同时保持良好的跨模态对齐能力。
23
+ * **基座模型**:
24
+ - 文本编码器:`BAAI/bge-base-zh-v1.5`
25
+ - 视觉编码器:`openai/clip-vit-base-patch32`
26
+ * **适用场景**:中文图文检索、多模态搜索、内容理解、边缘设备部署等资源受限环境。
27
 
28
+ ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ ## 📦 项目结构
31
 
32
+ * mini-embed-vision/
33
 
34
+ ├── Model.py # 多模态模型结构定义
35
+ ├── train.py # 训练脚本
36
+ ├── data.py # 数据加载与预处理(基于 COCO128,支持扩展)
37
+ ├── example/ # 使用示例
38
+ │ ├── test_embed_image.py # 图像嵌入示例
39
+ │ └── test_image_text_ser.py # 图文检索示例
40
+ ├── requirements.txt # 依赖库
41
+ └── README.md # 本文档
42
 
43
+ > 兼容 `transformers`、`peft`、`datasets` 等主流 Hugging Face 生态库。
44
 
45
+ ---
46
 
47
+ ## 🚀 快速开始
48
 
49
+ ### 0. 环境搭建
50
 
51
+ #### 0.1 克隆代码
52
+ ```bash
53
+ git clone https://github.com/SyJarvis/mini-embed-vision.git
54
+ cd mini-embed-vision
55
+ ```
56
 
57
+ #### 0.2 安装依赖
58
 
59
+ ```
60
+ pip install -r requirements.txt
61
+ ```
62
 
 
63
 
 
64
 
65
+ ### 1. 使用预训练模型
66
 
67
+ #### 1.1 下载模型(推荐使用国内镜像加速)
68
 
69
+ > 💡 由于 Hugging Face 官方服务器访问受限,建议通过 HF-Mirror 镜像下载。
70
 
71
+ 方法一:使用 huggingface-cli + 镜像
72
 
73
+ ```bash
74
+ export HF_ENDPOINT=https://hf-mirror.com
75
+ huggingface-cli download --resume-download syjarvis/mini-embed-vision-v1.0 --local-dir ./mini-embed-vision-v1.0
76
+ ```
77
 
78
+ 方法二:使用modelscope
79
 
80
+ ```bash
81
+ modelscope download --model shangye/mini-embed-vision-v1.0
82
+ ```
83
 
84
+ #### 1.2 运行示例
85
 
86
+ * 图像嵌入提取
87
 
88
+ ```bash
89
+ python example/test_embed_image.py
90
+ ```
91
 
92
+ * 图文检索示例
93
 
94
+ ```
95
+ python example/test_image_text_ser.py
96
+ ```
97
 
 
98
 
 
99
 
100
+ ### 2. 推理示例(代码)
101
 
102
+ #### 图像嵌入提取
103
 
104
+ ```python
105
+ from PIL import Image
106
+ from transformers import AutoTokenizer, AutoImageProcessor, AutoModel
107
+ import requests
108
+ import torch
109
 
110
+ model_dir = "./mini-embed-vision-v1.0"
111
 
112
+ tokenizer = AutoTokenizer.from_pretrained(model_dir)
113
+ image_processor = AutoImageProcessor.from_pretrained(model_dir)
114
+ model = AutoModel.from_pretrained(model_dir, trust_remote_code=True).to("cuda")
115
 
116
+ url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
117
+ image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
118
+ inputs = image_processor(image, return_tensors="pt").to("cuda")
119
 
120
+ with torch.no_grad():
121
+ emb = model.encode_image(inputs["pixel_values"]) # shape: [1, 768]
122
 
123
+ print("✅ 图像嵌入形状:", emb.shape)
124
+ print("✅ 嵌入范数(应为 1.0):", torch.norm(emb, dim=-1).item())
125
+ ```
126
 
127
+ #### 多模态图文检索
128
 
129
+ ```python
130
+ from PIL import Image
131
+ from transformers import AutoTokenizer, AutoImageProcessor, AutoModel
132
+ import requests
133
+ import torch
134
 
135
+ model_dir = "./mini-embed-vision-v1.0"
136
+ model = AutoModel.from_pretrained(model_dir, trust_remote_code=True).to("cuda")
137
+ tokenizer = AutoTokenizer.from_pretrained(model_dir)
138
+ image_processor = AutoImageProcessor.from_pretrained(model_dir)
139
 
140
+ # 图像
141
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
142
+ image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
143
+ image_inputs = image_processor(image, return_tensors="pt").to("cuda")
144
 
145
+ # 文本查询
146
+ queries = [
147
+ "两只猫坐在沙发上",
148
+ "一只狗在草地上奔跑",
149
+ "可爱的猫咪",
150
+ "海洋中的鲸鱼",
151
+ "室内宠物"
152
+ ]
153
 
154
+ # 编码图像
155
+ with torch.no_grad():
156
+ image_embedding = model.get_image_features(**image_inputs) # [1, 768]
157
 
158
+ # 编码文本
159
+ text_embeddings = []
160
+ for text in queries:
161
+ encoded = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512).to("cuda")
162
+ with torch.no_grad():
163
+ emb = model.get_text_features(**encoded) # [1, 768]
164
+ text_embeddings.append(emb)
165
 
166
+ text_embeddings = torch.cat(text_embeddings, dim=0) # [N, 768]
167
 
168
+ # 计算相似度(已 L2 归一化,点积 = 余弦相似度)
169
+ similarities = torch.matmul(image_embedding, text_embeddings.T).squeeze(0)
 
 
 
170
 
171
+ # 排序输出
172
+ print("\n🔍 图文检索结果(按相关性排序):")
173
+ results = sorted(zip(queries, similarities.tolist()), key=lambda x: x[1], reverse=True)
174
+ for i, (query, score) in enumerate(results, 1):
175
+ print(f"{i}. {query} → 相似度: {score:.4f}")
176
+ ```
177
 
 
178
 
 
179
 
180
+ ### 3. 从头训练模型
181
 
182
+ 🛠️ 训练脚本位于 train.py, 现提供了COCO128 数据集。欢迎提交 PR 扩展更多数据集或训练策略。
183
 
184
+ 训练命令
185
 
186
+ ```bash
187
+ python train.py
188
+ ```
189
 
 
190
 
 
191
 
192
+ ## **📝 更新日志**
193
 
194
+ <details close>
195
+ <summary><b>2025-10-20</b></summary>
196
+ * 实现了基础的多模态嵌入模型
197
+ * 支持图像/文本嵌入提取与多模态检索
198
+ * 发布V1.0预训练模型到Hugging Face Hub
199
+ </details>
200
 
 
201
 
 
202
 
203
+ ## 📌 Acknowledge
204
 
205
+ > [!NOTE]
206
+ > 如果觉得`miniembed-vision`对您有所帮助,可以在 GitHub 上加一个⭐<br/>
207
+ > 因水平有限难免疏漏,欢迎在Issues交流指正或提交PR改进项目<br/>
208
 
 
209
 
 
210
 
211
+ ## **📜 许可证**
212
 
213
+ 本项目采用 [Apache License 2.0](LICENSE) 开源协议。
214
 
 
215
 
 
216
 
 
217
 
218
+ ## 🙏 致谢
219
 
220
+ * [BAAI/bge-base-zh-v1.5](https://huggingface.co/BAAI/bge-base-zh-v1.5)
221
+ * [OpenAI CLIP](https://github.com/openai/CLIP)
222
+ * [contrastors](https://github.com/nomic-ai/contrastors)