Yosemat commited on
Commit
8eeaa19
1 Parent(s): 2b94143

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ SimHei.ttf filter=lfs diff=lfs merge=lfs -text
37
+ examples/dubai.png filter=lfs diff=lfs merge=lfs -text
38
+ examples/liuxiang.mp4 filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ pipeline_tag: visual-question-answering
4
+ ---
5
+
6
+
7
+ <p align="center">
8
+ <img src="logo_en.png" width="600"/>
9
+ <p>
10
+
11
+ <p align="center">
12
+ <b><font size="6">InternLM-XComposer-2.5</font></b>
13
+ <p>
14
+
15
+ <div align="center">
16
+
17
+ [💻Github Repo](https://github.com/InternLM/InternLM-XComposer)
18
+
19
+ [Online Demo](https://huggingface.co/spaces/Willow123/InternLM-XComposer)
20
+
21
+ [Paper](https://huggingface.co/papers/2407.03320)
22
+
23
+ </div>
24
+
25
+ **InternLM-XComposer2.5** excels in various text-image comprehension and composition applications, achieving GPT-4V level capabilities with merely 7B LLM backend. IXC2.5 is trained with 24K interleaved image-text contexts, it can seamlessly extend to 96K long contexts via RoPE extrapolation. This long-context capability allows IXC-2.5 to excel in tasks requiring extensive input and output contexts.
26
+
27
+
28
+ ### Import from Transformers
29
+ To load the InternLM-XComposer2-4KHD model using Transformers, use the following code:
30
+ ```python
31
+ import torch
32
+ from transformers import AutoTokenizer, AutoModelForCausalLM
33
+ ckpt_path = "internlm/internlm-xcomposer2d5-7b"
34
+ tokenizer = AutoTokenizer.from_pretrained(ckpt_path, trust_remote_code=True).cuda()
35
+ # Set `torch_dtype=torch.floatb16` to load model in bfloat16, otherwise it will be loaded as float32 and might cause OOM Error.
36
+ model = AutoModelForCausalLM.from_pretrained(ckpt_path, torch_dtype=torch.bfloat16, trust_remote_code=True).cuda()
37
+ model = model.eval()
38
+ ```
39
+
40
+ ## Quickstart
41
+
42
+ We provide a simple example to show how to use InternLM-XComposer2.5 with 🤗 Transformers.
43
+
44
+ <details>
45
+ <summary>
46
+ <b>Video Understanding</b>
47
+ </summary>
48
+
49
+ ```python
50
+ import torch
51
+ from transformers import AutoModel, AutoTokenizer
52
+
53
+ torch.set_grad_enabled(False)
54
+
55
+ # init model and tokenizer
56
+ model = AutoModel.from_pretrained('internlm/internlm-xcomposer2d5-7b', torch_dtype=torch.bfloat16, trust_remote_code=True).cuda().eval()
57
+ tokenizer = AutoTokenizer.from_pretrained('internlm/internlm-xcomposer2d5-7b', trust_remote_code=True)
58
+ model.tokenizer = tokenizer
59
+
60
+ query = 'Here are some frames of a video. Describe this video in detail'
61
+ image = ['./examples/liuxiang.mp4',]
62
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
63
+ response, his = model.chat(tokenizer, query, image, do_sample=False, num_beams=3, use_meta=True)
64
+ print(response)
65
+ #The video opens with a shot of an athlete, dressed in a red and yellow uniform with the word "CHINA" emblazoned across the front, preparing for a race.
66
+ #The athlete, Liu Xiang, is seen in a crouched position, focused and ready, with the Olympic rings visible in the background, indicating the prestigious setting of the Olympic Games. As the race commences, the athletes are seen sprinting towards the hurdles, their determination evident in their powerful strides.
67
+ #The camera captures the intensity of the competition, with the athletes' numbers and times displayed on the screen, providing a real-time update on their performance. The race reaches a climax as Liu Xiang, still in his red and yellow uniform, triumphantly crosses the finish line, his arms raised in victory.
68
+ #The crowd in the stands erupts into cheers, their excitement palpable as they witness the athlete's success. The video concludes with a close-up shot of Liu Xiang, still basking in the glory of his victory, as the Olympic rings continue to symbolize the significance of the event.
69
+
70
+ query = 'tell me the athlete code of Liu Xiang'
71
+ image = ['./examples/liuxiang.mp4',]
72
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
73
+ response, _ = model.chat(tokenizer, query, image, history=his, do_sample=False, num_beams=3, use_meta=True)
74
+ print(response)
75
+ #The athlete code of Liu Xiang, as displayed on his uniform in the video, is "1363".
76
+ ```
77
+
78
+ </details>
79
+
80
+ <details>
81
+ <summary>
82
+ <b>Multi-Image Mutli-Tune Dialog</b>
83
+ </summary>
84
+
85
+ ```python
86
+ import torch
87
+ from transformers import AutoModel, AutoTokenizer
88
+
89
+ torch.set_grad_enabled(False)
90
+
91
+ # init model and tokenizer
92
+ model = AutoModel.from_pretrained('internlm/internlm-xcomposer2d5-7b', torch_dtype=torch.bfloat16, trust_remote_code=True).cuda().eval()
93
+ tokenizer = AutoTokenizer.from_pretrained('internlm/internlm-xcomposer2d5-7b', trust_remote_code=True)
94
+ model.tokenizer = tokenizer
95
+
96
+ query = 'Image1 <ImageHere>; Image2 <ImageHere>; Image3 <ImageHere>; I want to buy a car from the three given cars, analyze their advantages and weaknesses one by one'
97
+ image = ['./examples/cars1.jpg',
98
+ './examples/cars2.jpg',
99
+ './examples/cars3.jpg',]
100
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
101
+ response, his = model.chat(tokenizer, query, image, do_sample=False, num_beams=3, use_meta=True)
102
+ print(response)
103
+ #To analyze the advantages and disadvantages of each car, we need to consider factors such as brand reputation, performance, design, cost, and maintenance.
104
+ #1. Mercedes-Benz: - Advantages: Known for its luxury and reliability, the Mercedes-Benz brand offers a high level of comfort, advanced technology, and superior craftsmanship. The vehicle in the image appears to be an SUV, which is versatile for both city driving and off-road conditions. - Disadvantages: Typically, Mercedes-Benz vehicles are more expensive compared to other brands, and they may require more frequent maintenance due to their luxury status.
105
+ #2. Bugatti: - Advantages: Bugatti is renowned for producing some of the fastest and most powerful cars in the world. The vehicle in the image is a sports car, likely offering an exhilarating driving experience with its high-performance engine and advanced aerodynamics. - Disadvantages: Bugatti cars are extremely expensive, making them less accessible to the average consumer. They also require specialized knowledge for maintenance and may not be suitable for everyday driving due to their high-performance nature.
106
+ #3. BMW: - Advantages: BMW is a well-respected manufacturer known for its innovative engineering and design. The car in the image appears to be an electric vehicle (EV), which offers advantages such as lower emissions, reduced noise pollution, and potentially lower operating costs. - Disadvantages: EVs like the one in the image may have a shorter range compared to traditional gasoline-powered vehicles, limiting their suitability for long-distance travel.
107
+ #Additionally, the initial cost of purchasing an EV can be higher than that of a conventional car. In conclusion, each car has its own set of advantages and disadvantages. The Mercedes-Benz offers luxury and versatility, the Bugatti provides high performance and exclusivity, and the BMW represents innovation in electric vehicle technology. The choice ultimately depends on the buyer's priorities, such as comfort, performance, environmental impact, and budget.
108
+
109
+ query = 'Image4 <ImageHere>; How about the car in Image4'
110
+ image.append('./examples/cars4.jpg')
111
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
112
+ response, _ = model.chat(tokenizer, query, image, do_sample=False, num_beams=3, history= his, use_meta=True)
113
+ print(response)
114
+ #The car in Image4 is a red sports car, which appears to be a Ferrari. Ferrari is a renowned Italian manufacturer known for producing some of the most iconic and high-performance sports cars in the world. - Advantages: Ferrari vehicles are synonymous with speed, luxury, and engineering excellence.
115
+ #The car in the image likely offers an exhilarating driving experience with its powerful engine, advanced aerodynamics, and high-quality craftsmanship. The red color adds to the car's aesthetic appeal, making it stand out on the road. - Disadvantages: Ferrari cars are extremely expensive, making them less accessible to the average consumer.
116
+ #They also require specialized knowledge for maintenance and may not be suitable for everyday driving due to their high-performance nature. In conclusion, the Ferrari in Image4 represents a pinnacle of automotive engineering and design, offering unmatched performance and luxury.
117
+ #However, its high cost and specialized maintenance requirements make it less practical for everyday use compared to the other vehicles in the images.
118
+ ```
119
+
120
+
121
+ </details>
122
+
123
+ <details>
124
+ <summary>
125
+ <b>High Resolution Image Understanding</b>
126
+ </summary>
127
+
128
+ ```python
129
+ import torch
130
+ from transformers import AutoModel, AutoTokenizer
131
+
132
+ torch.set_grad_enabled(False)
133
+
134
+ # init model and tokenizer
135
+ model = AutoModel.from_pretrained('internlm/internlm-xcomposer2d5-7b', torch_dtype=torch.bfloat16, trust_remote_code=True).cuda().eval()
136
+ tokenizer = AutoTokenizer.from_pretrained('internlm/internlm-xcomposer2d5-7b', trust_remote_code=True)
137
+ model.tokenizer = tokenizer
138
+
139
+ query = 'Analyze the given image in a detail manner'
140
+ image = ['./examples/dubai.png']
141
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
142
+ response, _ = model.chat(tokenizer, query, image, do_sample=False, num_beams=3, use_meta=True)
143
+ print(response)
144
+ #The infographic is a visual representation of various facts about Dubai. It begins with a statement about Palm Jumeirah, highlighting it as the largest artificial island visible from space. It then provides a historical context, noting that in 1968, there were only a few cars in Dubai, contrasting this with the current figure of more than 1.5 million vehicles.
145
+ #The infographic also points out that Dubai has the world's largest Gold Chain, with 7 of the top 10 tallest hotels located there. Additionally, it mentions that the crime rate is near 0%, and the income tax rate is also 0%, with 20% of the world's total cranes operating in Dubai. Furthermore, it states that 17% of the population is Emirati, and 83% are immigrants.
146
+ #The Dubai Mall is highlighted as the largest shopping mall in the world, with 1200 stores. The infographic also notes that Dubai has no standard address system, with no zip codes, area codes, or postal services. It mentions that the Burj Khalifa is so tall that its residents on top floors need to wait longer to break fast during Ramadan.
147
+ #The infographic also includes information about Dubai's climate-controlled City, with the Royal Suite at Burj Al Arab costing $24,000 per night. Lastly, it notes that the net worth of the four listed billionaires is roughly equal to the GDP of Honduras.
148
+
149
+ ```
150
+
151
+ </details>
152
+
153
+
154
+ <details>
155
+ <summary>
156
+ <b>Instruction to Webpage</b>
157
+ </summary>
158
+
159
+ ```python
160
+ import torch
161
+ from transformers import AutoModel, AutoTokenizer
162
+
163
+ torch.set_grad_enabled(False)
164
+
165
+ # init model and tokenizer
166
+ model = AutoModel.from_pretrained('internlm/internlm-xcomposer2d5-7b', torch_dtype=torch.bfloat16, trust_remote_code=True).cuda().eval()
167
+ tokenizer = AutoTokenizer.from_pretrained('internlm/internlm-xcomposer2d5-7b', trust_remote_code=True)
168
+ model.tokenizer = tokenizer
169
+
170
+ query = 'A website for Research institutions. The name is Shanghai AI lab. Top Navigation Bar is blue.Below left, an image shows the logo of the lab. In the right, there is a passage of text below that describes the mission of the laboratory.There are several images to show the research projects of Shanghai AI lab.'
171
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
172
+ response = model.write_webpage(query, seed=202, task='Instruction-aware Webpage Generation', repetition_penalty=3.0)
173
+ print(response)
174
+ # see the Instruction-aware Webpage Generation.html
175
+ ```
176
+
177
+ See the [Instruction to Webpage](https://github.com/InternLM/InternLM-XComposer/blob/main/examples/Instruction-aware_Webpage_Generation.html) results here.
178
+ </details>
179
+
180
+ <details>
181
+ <summary>
182
+ <b>Resume to Webpage</b>
183
+ </summary>
184
+
185
+ ```python
186
+ import torch
187
+ from transformers import AutoModel, AutoTokenizer
188
+
189
+ torch.set_grad_enabled(False)
190
+
191
+ # init model and tokenizer
192
+ model = AutoModel.from_pretrained('internlm/internlm-xcomposer2d5-7b', torch_dtype=torch.bfloat16, trust_remote_code=True).cuda().eval()
193
+ tokenizer = AutoTokenizer.from_pretrained('internlm/internlm-xcomposer2d5-7b', trust_remote_code=True)
194
+ model.tokenizer = tokenizer
195
+
196
+ ## the input should be a resume in markdown format
197
+ query = './examples/resume.md'
198
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
199
+ response = model.resume_2_webpage(query, seed=202, repetition_penalty=3.0)
200
+ print(response)
201
+ ```
202
+ See the [Resume to Webpage](https://github.com/InternLM/InternLM-XComposer/blob/main/examples/Resume-to-Personal_Page.html) results here.
203
+
204
+
205
+ </details>
206
+
207
+
208
+ <details>
209
+ <summary>
210
+ <b>Screenshot to Webpage</b>
211
+ </summary>
212
+
213
+ ```python
214
+ import torch
215
+ from transformers import AutoModel, AutoTokenizer
216
+
217
+ torch.set_grad_enabled(False)
218
+
219
+ # init model and tokenizer
220
+ model = AutoModel.from_pretrained('internlm/internlm-xcomposer2d5-7b', torch_dtype=torch.bfloat16, trust_remote_code=True).cuda().eval()
221
+ tokenizer = AutoTokenizer.from_pretrained('internlm/internlm-xcomposer2d5-7b', trust_remote_code=True)
222
+ model.tokenizer = tokenizer
223
+
224
+ query = 'Generate the HTML code of this web image with Tailwind CSS.'
225
+ image = ['./examples/screenshot.jpg']
226
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
227
+ response = model.screen_2_webpage(query, image, seed=202, repetition_penalty=3.0)
228
+ print(response)
229
+ ```
230
+ See the [Screenshot to Webpage](https://github.com/InternLM/InternLM-XComposer/blob/main/examples/Screenshot-to-Webpage.html) results here.
231
+
232
+ </details>
233
+
234
+
235
+
236
+ <details>
237
+ <summary>
238
+ <b>Write Article</b>
239
+ </summary>
240
+
241
+ ```python
242
+ import torch
243
+ from transformers import AutoModel, AutoTokenizer
244
+
245
+ torch.set_grad_enabled(False)
246
+
247
+ # init model and tokenizer
248
+ model = AutoModel.from_pretrained('internlm/internlm-xcomposer2d5-7b', torch_dtype=torch.bfloat16, trust_remote_code=True).cuda().eval()
249
+ tokenizer = AutoTokenizer.from_pretrained('internlm/internlm-xcomposer2d5-7b', trust_remote_code=True)
250
+ model.tokenizer = tokenizer
251
+
252
+ query = '阅读下面的材料,根据要求写作。 电影《长安三万里》的出现让人感慨,影片并未将重点全落在大唐风华上,也展现了恢弘气象的阴暗面,即旧门阀的资源垄断、朝政的日益衰败与青年才俊的壮志难酬。高适仕进无门,只能回乡>沉潜修行。李白虽得玉真公主举荐,擢入翰林,但他只是成为唐玄宗的御用文人,不能真正实现有益于朝政的志意。然而,片中高潮部分《将进酒》一节,人至中年、挂着肚腩的李白引众人乘仙鹤上天,一路从水面、瀑布飞升至银河进入仙>宫,李白狂奔着与仙人们碰杯,最后大家纵身飞向漩涡般的九重天。肉身的微贱、世路的“天生我材必有用,坎坷,拘不住精神的高蹈。“天生我材必有用,千金散尽还复来。” 古往今来,身处闲顿、遭受挫折、被病痛折磨,很多人都曾经历>了人生的“失意”,却反而成就了他们“诗意”的人生。对正在追求人生价值的当代青年来说,如何对待人生中的缺憾和困顿?诗意人生中又有怎样的自我坚守和自我认同?请结合“失意”与“诗意”这两个关键词写一篇文章。 要求:选准角度,确定>立意,明确文体,自拟标题;不要套作,不得抄袭;不得泄露个人信息;不少于 800 字。'
253
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
254
+ response = model.write_artical(query, seed=8192)
255
+ print(response)
256
+ #诗意人生,贵在坚守
257
+ #《菜根谭》有云:“闲时要有吃紧的心思,忙里要留吃闲工夫。”人生在世,总有失意之时,当面对缺憾和困顿,诗意地生活着才能为人生增添一抹亮色。何谓诗意地生活? 所谓诗意地生活,便是在于坚守本心、直面遗憾、超越自我,在失意中寻找人生价值。
258
+ #诗意地生活,需坚守本心,淡然处之。
259
+ #陶渊明曾执意辞去彭泽县令,归隐田园,“采菊东篱下,悠然见南山”,在山水间寄情自娱;王维面对仕途失意,终日沉醉于诗酒之中,“兴来每独往,胜事空自知”,在诗酒中闲逸自如;李白仕途不顺,被赐金放还,但他依旧豪气干云,“天生我才必有用,千金散尽还复来”,在失意中坦然豁达。坚守本心,便能在遭遇失意之时守住自己的精神家园,让生活充满诗意。反之,若不能坚守本心,而只是一味迎合世俗以求得升迁,那纵使身居高位,亦会丧失生活的乐趣。
260
+ #诗意地生活,需直面遗憾,超越自我。
261
+ #“西塞山前白鹭飞,桃花流水鳜鱼肥。青箬笠,绿柳枝,半斤酒,一纶丝。五湖四海皆如此,何妨到此处归。”白居易的《渔歌子》写出了多少人的愿望:没有权势纷扰,没有贫困凄凉,只有青山绿水、白鹭鸥鸟作伴,如此自由自在的生活令人神往。然而,白居易却并没有因此真的归隐山林,而是直面人生,超越自我,写下了一首首诗意而富有现实关怀的作品。如果白居易只顾逃避人生,那又怎会拥有“大弦嘈嘈如急雨,小弦切切如私语”的绝美比喻呢?如果白居易只顾归隐山林,那又怎会写出“此曲只应天上有,人间哪得配白居易”这样的诗句呢?
262
+ #诗意地生活,需直面遗憾,坚守本心。
263
+ #李文波患有渐冻症,医生说他活不过五年,但他没有因此放弃对音乐的热爱,而是与病魔作斗争,演奏出美妙的乐曲;孙家林自幼患有脑瘫,但他不甘于命运的捉弄,终成全国最美教师;史铁生饱受疾病折磨,但他仍能发出“我常常在我的心头清点,我有什么?”的叩问,并由此走上文学道路,为后世留下丰厚的文化遗产。这些人没有逃避,而是选择直面人生的缺憾,在坚守本心的同时超越自我,最终实现了自己的价值。
264
+ #诗意地生活,是于失意中坚守本心,于缺憾中超越自我。当面对人生的缺憾与挫折,坚守本心、超越自我的同时,也必将书写属于自己的辉煌篇章。
265
+ #愿你我都能诗意地生活着!
266
+
267
+ query = 'Please write a blog based on the title: French Pastries: A Sweet Indulgence'
268
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
269
+ response = model.write_artical(query, seed=8192)
270
+ print(response)
271
+ #French Pastries: A Sweet Indulgence
272
+ #The French are well known for their love of pastries, and it’s a love that is passed down through generations. When one visits France, they are treated to an assortment of baked goods that can range from the delicate macaron to the rich and decadent chocolate mousse. While there are many delicious types of pastries found in France, five stand out as being the most iconic. Each of these pastries has its own unique qualities that make it special.
273
+ #1. Croissant
274
+ #One of the most famous pastries from France is the croissant. It is a buttery, flaky pastry that is best enjoyed fresh from the bakery. The dough is laminated with butter, giving it its signature layers. Croissants are typically eaten for breakfast or brunch, often accompanied by coffee or hot chocolate.
275
+ #2. Macaron
276
+ #The macaron is a small, delicate French confection made from almond flour, powdered sugar, and egg whites. The macaron itself is sandwiched with a ganache or jam filling. They come in a variety of colors and flavors, making them a popular choice for both casual snacking and upscale desserts.
277
+ #3. Madeleine
278
+ #The madeleine is a small shell-shaped cake that is light and sponge-like. It is often flavored with lemon or orange zest and sometimes dipped in chocolate. Madeleines are perfect for an afternoon snack with tea or coffee.
279
+ #4. Éclair
280
+ #The éclair is a long, thin pastry filled with cream and topped with chocolate glaze. It is a classic French treat that is both sweet and satisfying. Éclairs can be found in bakeries all over France and are often enjoyed with a cup of hot chocolate.
281
+ #5. Tarte Tatin
282
+ #The tarte Tatin is an apple tart that is known for its caramelized apples and puff pastry crust. It is named after the Tatin sisters who created the recipe in the late 19th century. Tarte Tatin is best served warm with a scoop of vanilla ice cream.
283
+ #These pastries are just a few of the many delicious treats that France has to offer. Whether you are a seasoned traveler or a first-time visitor, indulging in French pastries is a must-do activity. So go ahead, treat yourself—you deserve it!
284
+ ```
285
+
286
+ </details>
287
+
288
+
289
+ ### Open Source License
290
+ The code is licensed under Apache-2.0, while model weights are fully open for academic research and also allow free commercial usage. To apply for a commercial license, please fill in the application form (English)/申请表(中文). For other questions or collaborations, please contact internlm@pjlab.org.cn.
SimHei.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:336a838f4a78e150826be608dae69de59d50948c3d2b71760e096ae764154bdc
3
+ size 9751960
added_tokens.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|action_end|>": 92547,
3
+ "<|action_start|>": 92546,
4
+ "<|im_end|>": 92545,
5
+ "<|im_start|>": 92544,
6
+ "<|interpreter|>": 92548,
7
+ "<|plugin|>": 92549
8
+ }
build_mlp.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import re
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from transformers import CLIPVisionModel
7
+
8
+
9
+ def build_vision_tower():
10
+ vision_tower = "internlm/internlm-xcomposer2d5-clip"
11
+ return CLIPVisionTower(vision_tower)
12
+
13
+
14
+ def build_vision_projector():
15
+ projector_type = "mlp2x_gelu"
16
+ mm_hidden_size = 4096
17
+ mid_hidden_size = 4096
18
+ hidden_size = 4096
19
+
20
+ mlp_gelu_match = re.match(r"^mlp(\d+)x_gelu$", projector_type)
21
+ if mlp_gelu_match:
22
+ mlp_depth = int(mlp_gelu_match.group(1))
23
+ modules = [nn.Linear(mm_hidden_size, mid_hidden_size)]
24
+ for _ in range(1, mlp_depth):
25
+ modules.append(nn.GELU())
26
+ modules.append(nn.Linear(mid_hidden_size, mid_hidden_size))
27
+
28
+ return nn.Sequential(*modules)
29
+
30
+ if projector_type == "identity":
31
+ return IdentityMap()
32
+
33
+ raise ValueError(f"Unknown projector type: {projector_type}")
34
+
35
+
36
+ class IdentityMap(nn.Module):
37
+ def __init__(self):
38
+ super().__init__()
39
+
40
+ def forward(self, x, *args, **kwargs):
41
+ return x
42
+
43
+ @property
44
+ def config(self):
45
+ return {"mm_projector_type": "identity"}
46
+
47
+
48
+ class CLIPVisionTower(nn.Module):
49
+ def __init__(self, vision_tower):
50
+ super().__init__()
51
+
52
+ self.is_loaded = False
53
+
54
+ self.vision_tower_name = vision_tower
55
+ # self.conv_dim = 8192
56
+ # self.conv = torch.nn.Conv2d(1024, self.conv_dim,3,2,1)
57
+ self.select_layer = -1
58
+ self.select_feature = "patch"
59
+ self.load_model()
60
+
61
+ def load_model(self):
62
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
63
+ self.vision_tower.requires_grad_(False)
64
+
65
+ self.is_loaded = True
66
+
67
+ def resize_pos(self):
68
+ print("Dummy Resized")
69
+
70
+ def feature_select(self, image_forward_outs):
71
+ image_features = image_forward_outs.hidden_states[self.select_layer]
72
+ if self.select_feature == "patch":
73
+ image_features = image_features[:, 1:]
74
+ elif self.select_feature == "cls_patch":
75
+ image_features = image_features
76
+ else:
77
+ raise ValueError(f"Unexpected select feature: {self.select_feature}")
78
+ return image_features
79
+
80
+ def forward(self, images, glb_GN, sub_GN) -> tuple[torch.Tensor, list[int]]:
81
+ if not self.is_loaded:
82
+ self.load_model()
83
+ assert type(images) is list
84
+ shapes = []
85
+ input_imgs = []
86
+ for img in images:
87
+ _, C, H, W = img.shape
88
+ shapes.append([H // 560, W // 560])
89
+ sub_img = (
90
+ img.reshape(1, 3, H // 560, 560, W // 560, 560)
91
+ .permute(0, 2, 4, 1, 3, 5)
92
+ .reshape(-1, 3, 560, 560)
93
+ .contiguous()
94
+ )
95
+ glb_img = torch.nn.functional.interpolate(
96
+ img.float(),
97
+ size=(560, 560),
98
+ mode="bicubic",
99
+ ).to(sub_img.dtype)
100
+ input_imgs.append(glb_img)
101
+ input_imgs.append(sub_img)
102
+ input_imgs = torch.cat(input_imgs, dim=0)
103
+
104
+ image_forward_outs = self.vision_tower(
105
+ input_imgs.to(device=self.device, dtype=self.dtype),
106
+ output_hidden_states=True,
107
+ )
108
+ image_features = self.feature_select(image_forward_outs).to(
109
+ input_imgs.dtype
110
+ ) ### B*?, N, C
111
+ _, N, C = image_features.shape
112
+ H = int(math.sqrt(N))
113
+ assert N == 40**2
114
+
115
+ output_imgs = []
116
+ output_len = []
117
+ for [h, w] in shapes:
118
+ B_ = h * w
119
+ glb_img = image_features[:1] ### 1, N, C
120
+ glb_img = (
121
+ glb_img.reshape(1, H, H, C)
122
+ .reshape(1, H // 2, 2, H // 2, 2, C)
123
+ .contiguous()
124
+ .permute(0, 1, 3, 2, 4, 5)
125
+ .reshape(1, H // 2, H // 2, 4 * C)
126
+ .contiguous()
127
+ )
128
+ temp_glb_GN = sub_GN.repeat(1, H // 2, 1, 1)
129
+ glb_img = torch.cat([glb_img, temp_glb_GN], dim=2).reshape(1, -1, 4 * C)
130
+
131
+ sub_img = image_features[1 : 1 + B_] ### ?, N, C
132
+ sub_img = (
133
+ sub_img.reshape(B_, H, H, C)
134
+ .reshape(B_, H // 2, 2, H // 2, 2, C)
135
+ .contiguous()
136
+ .permute(0, 1, 3, 2, 4, 5)
137
+ .reshape(B_, -1, 4 * C)
138
+ .contiguous()
139
+ )
140
+ sub_img = (
141
+ sub_img.reshape(1, h, w, 20, 20, -1)
142
+ .permute(0, 1, 3, 2, 4, 5)
143
+ .reshape(1, h * 20, w * 20, 4 * C)
144
+ )
145
+ temp_sub_GN = sub_GN.repeat(1, h * 20, 1, 1)
146
+ sub_img = torch.cat([sub_img, temp_sub_GN], dim=2).reshape(1, -1, 4 * C)
147
+
148
+ output_imgs.append(torch.cat([glb_img, glb_GN, sub_img], dim=1))
149
+ temp_len = int((h * w + 1) * 400 + 1 + (h + 1) * 20)
150
+ assert temp_len == output_imgs[-1].shape[1]
151
+ output_len.append(temp_len)
152
+
153
+ image_features = image_features[1 + h * w :]
154
+
155
+ output_imgs = torch.cat(output_imgs, dim=1)
156
+
157
+ return output_imgs, output_len
158
+
159
+ @property
160
+ def dummy_feature(self):
161
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
162
+
163
+ @property
164
+ def dtype(self):
165
+ return self.vision_tower.dtype
166
+
167
+ @property
168
+ def device(self):
169
+ return self.vision_tower.device
170
+
171
+ @property
172
+ def config(self):
173
+ if self.is_loaded:
174
+ return self.vision_tower.config
175
+ else:
176
+ return self.cfg_only
177
+
178
+ @property
179
+ def hidden_size(self):
180
+ return self.config.hidden_size
181
+
182
+ @property
183
+ def num_patches(self):
184
+ return (self.config.image_size // self.config.patch_size) ** 2
185
+
186
+
187
+ class PLoRA(nn.Linear):
188
+ def __init__(
189
+ self,
190
+ in_features: int,
191
+ out_features: int,
192
+ bias: bool = True,
193
+ device=None,
194
+ dtype=None,
195
+ lora_r=8,
196
+ lora_alpha=16,
197
+ lora_dropout=0.05,
198
+ lora_len=0,
199
+ **kwargs,
200
+ ) -> None:
201
+ super().__init__(in_features, out_features, bias, device, dtype)
202
+ self.lora_r = lora_r
203
+ self.lora_alpha = lora_alpha
204
+ self.lora_len = lora_len
205
+ if lora_dropout > 0.0:
206
+ self.lora_dropout = nn.Dropout(p=lora_dropout)
207
+ else:
208
+ self.lora_dropout = lambda x: x
209
+ self.lora_scaling = self.lora_alpha / self.lora_r
210
+
211
+ self.Plora_A = nn.Linear(
212
+ in_features, self.lora_r, bias=False, device=device, dtype=dtype
213
+ )
214
+ self.Plora_B = nn.Linear(
215
+ self.lora_r, out_features, bias=False, device=device, dtype=dtype
216
+ )
217
+
218
+ self.lora_sft_A = nn.Linear(
219
+ in_features, 256, bias=False, device=device, dtype=dtype
220
+ )
221
+ self.lora_sft_B = nn.Linear(
222
+ 256, out_features, bias=False, device=device, dtype=dtype
223
+ )
224
+
225
+ self.lora_dpo_A = nn.Linear(
226
+ in_features, 256, bias=False, device=device, dtype=dtype
227
+ )
228
+ self.lora_dpo_B = nn.Linear(
229
+ 256, out_features, bias=False, device=device, dtype=dtype
230
+ )
231
+
232
+ self.lora_web_A = nn.Linear(
233
+ in_features, 512, bias=False, device=device, dtype=dtype
234
+ )
235
+ self.lora_web_B = nn.Linear(
236
+ 512, out_features, bias=False, device=device, dtype=dtype
237
+ )
238
+
239
+ self.reset_parameters()
240
+
241
+ def reset_parameters(self):
242
+ if hasattr(self, "lora_A"):
243
+ # initialize A the same way as the default for nn.Linear and B to zero
244
+ nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5))
245
+ nn.init.zeros_(self.lora_B.weight)
246
+ # print ("lora weight init {} {}".format(torch.mean(self.lora_A.weight), torch.mean(self.lora_B.weight)))
247
+
248
+ def forward(self, x, im_mask=None, infer_mode="base"):
249
+ B, N, C = x.shape
250
+ im_mask = im_mask.view(-1)
251
+ x = x.reshape(-1, C)
252
+ res = super().forward(x)
253
+ if infer_mode == "web":
254
+ res += self.lora_web_B(self.lora_web_A(x))
255
+ elif infer_mode == "write":
256
+ res += self.lora_sft_B(self.lora_sft_A(x))
257
+ res += self.lora_dpo_B(self.lora_dpo_A(x))
258
+ else:
259
+ pass
260
+ if im_mask is not None:
261
+ if torch.sum(im_mask) > 0:
262
+ part_x = x[im_mask]
263
+ res[im_mask] += (
264
+ self.Plora_B(self.Plora_A(self.lora_dropout(part_x)))
265
+ * self.lora_scaling
266
+ )
267
+ else:
268
+ part_x = x[:1]
269
+ res[:1] += self.Plora_B(self.Plora_A(self.lora_dropout(part_x))) * 0
270
+
271
+ return res.reshape(B, N, -1)
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/mnt/petrelfs/dongxiaoyi/gittest/temp_model/internlm-xcomposer2d5-7b",
3
+ "architectures": [
4
+ "InternLMXComposer2ForCausalLM"
5
+ ],
6
+ "attn_implementation": "flash_attention_2",
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_internlm_xcomposer2.InternLMXcomposer2Config",
9
+ "AutoModel": "modeling_internlm_xcomposer2.InternLMXComposer2ForCausalLM",
10
+ "AutoModelForCausalLM": "modeling_internlm_xcomposer2.InternLMXComposer2ForCausalLM"
11
+ },
12
+ "bias": false,
13
+ "bos_token_id": 1,
14
+ "eos_token_id": 2,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 4096,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 14336,
19
+ "max_length": 16384,
20
+ "max_position_embeddings": 24576,
21
+ "model_type": "internlm2",
22
+ "num_attention_heads": 32,
23
+ "num_hidden_layers": 32,
24
+ "num_key_value_heads": 8,
25
+ "pad_token_id": 2,
26
+ "rms_norm_eps": 1e-05,
27
+ "rope_scaling": {
28
+ "type": "dynamic",
29
+ "factor": 2.0
30
+ },
31
+ "rope_theta": 1000000,
32
+ "tie_word_embeddings": false,
33
+ "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.33.1",
35
+ "use_cache": false,
36
+ "vocab_size": 92544
37
+ }
configuration_internlm_xcomposer2.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on transformers/src/transformers/models/llama/configuration_llama.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ InternLM2 model configuration"""
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
25
+
26
+
27
+ class InternLMXcomposer2Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
30
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`InternLM2Model`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
70
+ Whether to tie weight embeddings
71
+ Example:
72
+
73
+ """
74
+ model_type = "internlm2"
75
+ _auto_class = "AutoConfig"
76
+
77
+ def __init__( # pylint: disable=W0102
78
+ self,
79
+ vocab_size=103168,
80
+ hidden_size=4096,
81
+ intermediate_size=11008,
82
+ num_hidden_layers=32,
83
+ num_attention_heads=32,
84
+ num_key_value_heads=None,
85
+ hidden_act="silu",
86
+ max_position_embeddings=2048,
87
+ initializer_range=0.02,
88
+ rms_norm_eps=1e-6,
89
+ use_cache=True,
90
+ pad_token_id=0,
91
+ bos_token_id=1,
92
+ eos_token_id=2,
93
+ tie_word_embeddings=False,
94
+ bias=True,
95
+ rope_theta=10000,
96
+ rope_scaling=None,
97
+ attn_implementation="flash_attention_2",
98
+ **kwargs,
99
+ ):
100
+ self.vocab_size = vocab_size
101
+ self.max_position_embeddings = max_position_embeddings
102
+ self.hidden_size = hidden_size
103
+ self.intermediate_size = intermediate_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.bias = bias
107
+
108
+ if num_key_value_heads is None:
109
+ num_key_value_heads = num_attention_heads
110
+ self.num_key_value_heads = num_key_value_heads
111
+
112
+ self.hidden_act = hidden_act
113
+ self.initializer_range = initializer_range
114
+ self.rms_norm_eps = rms_norm_eps
115
+ self.use_cache = use_cache
116
+ self.rope_theta = rope_theta
117
+ self.rope_scaling = rope_scaling
118
+ self._rope_scaling_validation()
119
+
120
+ self.attn_implementation = attn_implementation
121
+ if self.attn_implementation is None:
122
+ self.attn_implementation = "flash_attention_2"
123
+ super().__init__(
124
+ pad_token_id=pad_token_id,
125
+ bos_token_id=bos_token_id,
126
+ eos_token_id=eos_token_id,
127
+ tie_word_embeddings=tie_word_embeddings,
128
+ **kwargs,
129
+ )
130
+
131
+ def _rope_scaling_validation(self):
132
+ """
133
+ Validate the `rope_scaling` configuration.
134
+ """
135
+ if self.rope_scaling is None:
136
+ return
137
+
138
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
139
+ raise ValueError(
140
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
141
+ f"got {self.rope_scaling}"
142
+ )
143
+ rope_scaling_type = self.rope_scaling.get("type", None)
144
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
145
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
146
+ raise ValueError(
147
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
148
+ )
149
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
150
+ raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
examples/cars1.jpg ADDED
examples/cars2.jpg ADDED
examples/cars3.jpg ADDED
examples/cars4.jpg ADDED
examples/dubai.png ADDED

Git LFS Details

  • SHA256: d1791fdc7767a6e868da0e35d0158f02eae0c78229a0f4505580d756b4ea3929
  • Pointer size: 132 Bytes
  • Size of remote file: 2.8 MB
examples/liuxiang.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29e1448fe188d8cca2e85fd81c236c53fd61784063d93bc09e2301d33798937a
3
+ size 26855609
examples/resume.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Qidong Huang
2
+
3
+ Building No.7, USTC West CampusHefei, Anhui, China
4
+
5
+ Ph.D, University of Science and Technology of China
6
+
7
+ H (+86) 13085060686
8
+
9
+ B hqd0037@mail.ustc.edu.cn
10
+
11
+ # Short Biography
12
+
13
+ Qidong Huang is a PhD student at University of Science and Technology of China. He has published more than 7 papers at top1-tier conferences and journals, such as CVPR/ICCV/AAAI/TIP/TCSVT. His research interests focus on vision transfer learning (e.g., prompt learning for vision pretrained models) and artificial intelligence security (e.g., adversarial examples and anti-DeepFake). He is the reviewer of many top conferences (including CVPR, ICCV, ECCV) and top journals (TNNLS, PR).
14
+
15
+ # Education
16
+
17
+ |09/2020–present|PhD of Cyberspace Security, University of Science and Technology of China, Hefei, China, CAS Key Laboratory of Electromagnetic Space Information. Supervised by Prof. Weiming Zhang.|
18
+ |---|---|
19
+ |09/2016–06/2020|Bachelor of Information Security, School of Information Science and Technology, University of Science and Technology of China, Hefei, China.|
20
+
21
+ # Skills
22
+
23
+ - Expertise in vision prompt learning: I have been researching the prompt learning for large-scale vision pretrained models and published one paper on top-tier computer vision conferences, in which I propose DAM-VP, a data diversity-aware method for efficient and adaptive vision prompt learning. This work alleviates the mismatch between vision prompts and downstream data diversity.
24
+ - Expertise in artificial intelligence security: I have been studying artificial intelligence security since 2020, including adversarial attack&defense and anti-DeepFake. For adversarial attack, I propose SI-Adv, a shape-invariant attack for 3D point cloud recognition which great boosts the imperceptibility of adversarial examples. For adversarial defense, I propose a contrastive adversarial training framework for robust point cloud recognition named PointCAT. Besides, our work for improving adversarial robustness of masked autoencoders has been recently accepted by ICCV 2023. For anti-DeepFake, we are the first to propose the concept of “initiative defense” against DeepFakes by proactively protecting users’ facial privacy before the manipulation, unlike previous ex-post countermeasures like DeepFake detection.
25
+
26
+ # Publications (First Author)
27
+
28
+ Qidong Huang, Xiaoyi Dong, Dongdong Chen, Yinpeng Chen, Lu Yuan, Gang Hua, Weiming Zhang, Nenghai Yu. Improving Adversarial Robustness of Masked Autoencoders via Test-time Frequency-domain Prompting. International Conference on Computer Vision (ICCV), 2023.
29
+ Qidong Huang, Xiaoyi Dong, Dongdong Chen, Weiming Zhang, Feifei Wang, Gang Hua, Nenghai Yu. Diversity-Aware Meta Visual Prompting. Conference on Computer Vision and Pattern Recognition (CVPR), 2023.
30
+ Qidong Huang, Xiaoyi Dong, Dongdong Chen, Hang Zhou, Weiming Zhang, Nenghai Yu. Shape-invariant 3D Adversarial Point Clouds. Conference on Computer Vision and Pattern Recognition (CVPR), 2022.
31
+ ---
32
+ # Publications
33
+
34
+ Qidong Huang*, Jie Zhang*, Wenbo Zhou, Weiming Zhang, Nenghai Yu. Initiative Defense against Facial Manipulation. AAAI Conference on Artificial Intelligence (AAAI), 2021. (*Qidong Huang and Jie Zhang contribute equally.)
35
+ Qidong Huang, Xiaoyi Dong, Dongdong Chen, Hang Zhou, Weiming Zhang, Kui Zhang, Gang Hua, Nenghai Yu. PointCAT : Contrastive Adversarial Training for Robust Point Cloud Recognition. IEEE Transactions on Image Processing (TIP), Major Revision.
36
+ Kui Zhang, Hang Zhou, Jie Zhang, Qidong Huang, Weiming Zhang, Nenghai Yu. Ada3Diff : Defending against 3D Adversarial Point Clouds via Adaptive Diffusion. Under Review
37
+ Han Fang, Dongdong Chen, Qidong Huang, Jie Zhang, Zehua Ma, Weiming Zhang* and Nenghai Yu. Deep Template-based Watermarking. IEEE Transactions on Circuits and Systems for Video Technology (TCSVT), 2020.
38
+ Jie Zhang, Dongdong Chen, Qidong Huang, Jing Liao, Weiming Zhang, Huamin Feng, Gang Hua, Nenghai Yu. Poison ink : Robust and invisible backdoor attack. IEEE Transactions on Image Processing (TIP), 2022.
39
+
40
+ # Services
41
+
42
+ - Reviewer for CVPR 2022, 2023
43
+ - Reviewer for ICCV 2023
44
+ - Reviewer for ECCV 2022
45
+ - Reviewer for ICPR 2022
46
+ - Reviewer for IEEE Transactions on Neural Networks and Learning Systems (TNNLS)
47
+ - Reviewer for Pattern Recognition (PR)
48
+
49
+ # Awards & Honors
50
+
51
+ 2021 China National Scholarship
examples/screenshot.jpg ADDED
examples/test.py ADDED
File without changes
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "max_length": 16384,
6
+ "pad_token_id": 2,
7
+ "transformers_version": "4.33.1",
8
+ "use_cache": false
9
+ }
ixc_utils.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import numpy as np
4
+ import torchvision
5
+ from urllib.request import urlopen
6
+ from PIL import Image, ImageDraw, ImageFont
7
+ from torchvision.transforms.functional import InterpolationMode
8
+ import torchvision.transforms as transforms
9
+ from decord import VideoReader
10
+
11
+ def get_font():
12
+ truetype_url = 'https://huggingface.co/internlm/internlm-xcomposer2d5-7b/resolve/main/SimHei.ttf?download=true'
13
+ ff = urlopen(truetype_url)
14
+ font = ImageFont.truetype(ff, size=40)
15
+ return font
16
+
17
+ def padding_336(b, pad=336):
18
+ width, height = b.size
19
+ tar = int(np.ceil(height / pad) * pad)
20
+ top_padding = 0 # int((tar - height)/2)
21
+ bottom_padding = tar - height - top_padding
22
+ left_padding = 0
23
+ right_padding = 0
24
+ b = transforms.functional.pad(b, [left_padding, top_padding, right_padding, bottom_padding], fill=[255,255,255])
25
+
26
+ return b
27
+
28
+ def Image_transform(img, hd_num=25):
29
+ width, height = img.size
30
+ trans = False
31
+ if width < height:
32
+ img = img.transpose(Image.TRANSPOSE)
33
+ trans = True
34
+ width, height = img.size
35
+ ratio = (width/ height)
36
+ scale = 1
37
+ while scale*np.ceil(scale/ratio) <= hd_num:
38
+ scale += 1
39
+ scale -= 1
40
+ scale = min(np.ceil(width / 560), scale)
41
+ new_w = int(scale * 560)
42
+ new_h = int(new_w / ratio)
43
+ #print (scale, f'{height}/{new_h}, {width}/{new_w}')
44
+
45
+ img = transforms.functional.resize(img, [new_h, new_w],)
46
+ img = padding_336(img, 560)
47
+ width, height = img.size
48
+ if trans:
49
+ img = img.transpose(Image.TRANSPOSE)
50
+
51
+ return img
52
+
53
+
54
+ def Video_transform(img, hd_num=25):
55
+ width, height = img.size
56
+ trans = False
57
+ if width < height:
58
+ img = img.transpose(Image.TRANSPOSE)
59
+ trans = True
60
+ width, height = img.size
61
+ ratio = (width/ height)
62
+ scale = 1
63
+ new_h = int(scale * 560)
64
+ new_w = int(new_h * ratio)
65
+ #print (new_h, new_w)
66
+
67
+ img = transforms.functional.resize(img, [new_h, new_w],)
68
+ img = img.transpose(Image.TRANSPOSE)
69
+ img = padding_336(img, 560)
70
+ width, height = img.size
71
+ if not trans:
72
+ img = img.transpose(Image.TRANSPOSE)
73
+
74
+ return img
75
+
76
+ def frame2img(imgs, font):
77
+ new_imgs = []
78
+ for img in imgs:
79
+ w, h = img.size
80
+ scale = w/h
81
+ if w > h:
82
+ new_w = 560 * 2
83
+ new_h = int(560 * 2 / scale)
84
+ else:
85
+ new_w = int(560 * 2 * scale)
86
+ new_h = 560 * 2
87
+ img = transforms.functional.resize(img, [new_h, new_w],)
88
+ new_imgs.append(img)
89
+ imgs = new_imgs
90
+ new_w = 0
91
+ new_h = 0
92
+ pad = 40
93
+ if w > h:
94
+ for im in imgs:
95
+ w,h = im.size
96
+ new_w = max(new_w, w)
97
+ new_h += h + 10 + pad
98
+ new_img = Image.new('RGB', (new_w, new_h), 'white')
99
+ draw = ImageDraw.Draw(new_img)
100
+ curr_h = 0
101
+ for idx, im in enumerate(imgs):
102
+ w,h = im.size
103
+ new_img.paste(im, (0, pad + curr_h))
104
+ draw.text((0, curr_h ), f'<IMAGE {idx}>', font=font, fill='black')
105
+ if idx + 1 < len(imgs):
106
+ draw.line([(0, pad +curr_h + h +5), (new_w, pad +curr_h + h +5)], fill = 'black', width=2)
107
+ curr_h += h + 10 + pad
108
+ #print (new_w, new_h)
109
+ else:
110
+ for im in imgs:
111
+ w,h = im.size
112
+ new_w += w + 10
113
+ new_h = max(new_h, h)
114
+ new_h += pad
115
+ new_img = Image.new('RGB', (new_w, new_h), 'white')
116
+ draw = ImageDraw.Draw(new_img)
117
+ curr_w = 0
118
+ for idx, im in enumerate(imgs):
119
+ w,h = im.size
120
+ new_img.paste(im, (curr_w, pad))
121
+ draw.text((curr_w, 0), f'<IMAGE {idx}>', font=font, fill='black')
122
+ if idx + 1 < len(imgs):
123
+ draw.line([(curr_w + w + 5, 0), (curr_w + w + 5, new_h)], fill = 'black', width=2)
124
+ curr_w += w + 10
125
+ return new_img
126
+
127
+ def load_video(video_path, num_frm=32, start=None, end=None):
128
+ vid = VideoReader(video_path, num_threads=1)
129
+ fps = vid.get_avg_fps()
130
+ t_stride = int(round(float(fps) / int(1)))
131
+ start_idx = 0 if start is None else start
132
+ end_idx = len(vid) if end is None else end
133
+ all_pos = list(range(start_idx, end_idx, t_stride))
134
+ try:
135
+ images = [vid[i].numpy() for i in all_pos]
136
+ except:
137
+ images = [vid[i].asnumpy() for i in all_pos]
138
+ if len(images) > num_frm:
139
+ num_frm = min(num_frm, len(images))
140
+ step_size = len(images) / (num_frm + 1)
141
+ indices = [int(i*step_size) for i in range(num_frm)]
142
+ images = [images[i] for i in indices]
143
+ images = [Image.fromarray(arr) for arr in images]
144
+ return images
145
+
logo_en.png ADDED
modeling_internlm2.py ADDED
@@ -0,0 +1,1174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/modeling_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch InternLM2 model."""
17
+
18
+ import math
19
+ import warnings
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from einops import rearrange
26
+ from torch import nn
27
+ from transformers.activations import ACT2FN
28
+ from transformers.modeling_outputs import BaseModelOutputWithPast
29
+ from transformers.modeling_utils import PreTrainedModel
30
+ from transformers.utils import (
31
+ add_start_docstrings,
32
+ add_start_docstrings_to_model_forward,
33
+ logging,
34
+ )
35
+
36
+ try:
37
+ from transformers.generation.streamers import BaseStreamer
38
+ except: # noqa # pylint: disable=bare-except
39
+ BaseStreamer = None
40
+
41
+ from .build_mlp import PLoRA
42
+ from .configuration_internlm_xcomposer2 import (
43
+ InternLMXcomposer2Config as InternLM2Config,
44
+ )
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+ _CONFIG_FOR_DOC = "InternLM2Config"
49
+
50
+ flash_attn_func, flash_attn_varlen_func = None, None
51
+ pad_input, index_first_axis, unpad_input = None, None, None
52
+
53
+
54
+ def _import_flash_attn():
55
+ global flash_attn_func, flash_attn_varlen_func
56
+ global pad_input, index_first_axis, unpad_input
57
+ try:
58
+ from flash_attn import flash_attn_func as _flash_attn_func
59
+ from flash_attn import flash_attn_varlen_func as _flash_attn_varlen_func
60
+ from flash_attn.bert_padding import index_first_axis as _index_first_axis
61
+ from flash_attn.bert_padding import pad_input as _pad_input
62
+ from flash_attn.bert_padding import unpad_input as _unpad_input
63
+
64
+ flash_attn_func, flash_attn_varlen_func = (
65
+ _flash_attn_func,
66
+ _flash_attn_varlen_func,
67
+ )
68
+ pad_input, index_first_axis, unpad_input = (
69
+ _pad_input,
70
+ _index_first_axis,
71
+ _unpad_input,
72
+ )
73
+ except ImportError:
74
+ raise ImportError("flash_attn is not installed.")
75
+
76
+
77
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
78
+ def _get_unpad_data(attention_mask):
79
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
80
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
81
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
82
+ cu_seqlens = F.pad(
83
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
84
+ )
85
+ return (
86
+ indices,
87
+ cu_seqlens,
88
+ max_seqlen_in_batch,
89
+ )
90
+
91
+
92
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
93
+ def _make_causal_mask(
94
+ input_ids_shape: torch.Size,
95
+ dtype: torch.dtype,
96
+ device: torch.device,
97
+ past_key_values_length: int = 0,
98
+ ):
99
+ """
100
+ Make causal mask used for bi-directional self-attention.
101
+ """
102
+ bsz, tgt_len = input_ids_shape
103
+ mask = torch.full(
104
+ (tgt_len, tgt_len),
105
+ torch.tensor(torch.finfo(dtype).min, device=device),
106
+ device=device,
107
+ )
108
+ mask_cond = torch.arange(mask.size(-1), device=device)
109
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
110
+ mask = mask.to(dtype)
111
+
112
+ if past_key_values_length > 0:
113
+ mask = torch.cat(
114
+ [
115
+ torch.zeros(
116
+ tgt_len, past_key_values_length, dtype=dtype, device=device
117
+ ),
118
+ mask,
119
+ ],
120
+ dim=-1,
121
+ )
122
+ return mask[None, None, :, :].expand(
123
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
124
+ )
125
+
126
+
127
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
128
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
129
+ """
130
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
131
+ """
132
+ bsz, src_len = mask.size()
133
+ tgt_len = tgt_len if tgt_len is not None else src_len
134
+
135
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
136
+
137
+ inverted_mask = 1.0 - expanded_mask
138
+
139
+ return inverted_mask.masked_fill(
140
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
141
+ )
142
+
143
+
144
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->InternLM2
145
+ class InternLM2RMSNorm(nn.Module):
146
+ def __init__(self, hidden_size, eps=1e-6):
147
+ """
148
+ InternLM2RMSNorm is equivalent to T5LayerNorm
149
+ """
150
+ super().__init__()
151
+ self.weight = nn.Parameter(torch.ones(hidden_size))
152
+ self.variance_epsilon = eps
153
+
154
+ def forward(self, hidden_states):
155
+ input_dtype = hidden_states.dtype
156
+ hidden_states = hidden_states.to(torch.float32)
157
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
158
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
159
+ return self.weight * hidden_states.to(input_dtype)
160
+
161
+
162
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM2
163
+ class InternLM2RotaryEmbedding(nn.Module):
164
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
165
+ super().__init__()
166
+
167
+ self.dim = dim
168
+ self.max_position_embeddings = max_position_embeddings
169
+ self.base = base
170
+ inv_freq = 1.0 / (
171
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
172
+ )
173
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
174
+
175
+ # Build here to make `torch.jit.trace` work.
176
+ self._set_cos_sin_cache(
177
+ seq_len=max_position_embeddings,
178
+ device=self.inv_freq.device,
179
+ dtype=torch.get_default_dtype(),
180
+ )
181
+
182
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
183
+ self.max_seq_len_cached = seq_len
184
+ t = torch.arange(
185
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
186
+ )
187
+
188
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
189
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
190
+ emb = torch.cat((freqs, freqs), dim=-1)
191
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
192
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
193
+
194
+ def forward(self, x, seq_len=None):
195
+ # x: [bs, num_attention_heads, seq_len, head_size]
196
+ if seq_len > self.max_seq_len_cached:
197
+ self._set_cos_sin_cache(
198
+ seq_len=seq_len, device=x.device, dtype=torch.float32
199
+ )
200
+
201
+ return (
202
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
203
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
204
+ )
205
+
206
+
207
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->InternLM2
208
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
209
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
210
+
211
+ def __init__(
212
+ self,
213
+ dim,
214
+ max_position_embeddings=2048,
215
+ base=10000,
216
+ device=None,
217
+ scaling_factor=1.0,
218
+ ):
219
+ self.scaling_factor = scaling_factor
220
+ super().__init__(dim, max_position_embeddings, base, device)
221
+
222
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
223
+ self.max_seq_len_cached = seq_len
224
+ t = torch.arange(
225
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
226
+ )
227
+ t = t / self.scaling_factor
228
+
229
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
230
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
231
+ emb = torch.cat((freqs, freqs), dim=-1)
232
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
233
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
234
+
235
+
236
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM2
237
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
238
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
239
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
240
+ """
241
+
242
+ def __init__(
243
+ self,
244
+ dim,
245
+ max_position_embeddings=2048,
246
+ base=10000,
247
+ device=None,
248
+ scaling_factor=1.0,
249
+ ):
250
+ self.scaling_factor = scaling_factor
251
+ super().__init__(dim, max_position_embeddings, base, device)
252
+
253
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
254
+ self.max_seq_len_cached = seq_len
255
+
256
+ if seq_len > self.max_position_embeddings:
257
+ base = self.base * (
258
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
259
+ - (self.scaling_factor - 1)
260
+ ) ** (self.dim / (self.dim - 2))
261
+ inv_freq = 1.0 / (
262
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
263
+ )
264
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
265
+
266
+ t = torch.arange(
267
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
268
+ )
269
+
270
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
271
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
272
+ emb = torch.cat((freqs, freqs), dim=-1)
273
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
274
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
275
+
276
+
277
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
278
+ def rotate_half(x):
279
+ """Rotates half the hidden dims of the input."""
280
+ x1 = x[..., : x.shape[-1] // 2]
281
+ x2 = x[..., x.shape[-1] // 2 :]
282
+ return torch.cat((-x2, x1), dim=-1)
283
+
284
+
285
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
286
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
287
+ """Applies Rotary Position Embedding to the query and key tensors."""
288
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
289
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
290
+ q_embed = (q * cos) + (rotate_half(q) * sin)
291
+ k_embed = (k * cos) + (rotate_half(k) * sin)
292
+ return q_embed, k_embed
293
+
294
+
295
+ class InternLM2MLP(nn.Module):
296
+ def __init__(self, config):
297
+ super().__init__()
298
+ self.config = config
299
+ self.hidden_size = config.hidden_size
300
+ self.intermediate_size = config.intermediate_size
301
+ # self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
302
+ # self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
303
+ # self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
304
+
305
+ self.w1 = PLoRA(
306
+ self.hidden_size,
307
+ self.intermediate_size,
308
+ bias=False,
309
+ lora_r=256,
310
+ lora_alpha=256,
311
+ lora_len=1225,
312
+ )
313
+ self.w3 = PLoRA(
314
+ self.hidden_size,
315
+ self.intermediate_size,
316
+ bias=False,
317
+ lora_r=256,
318
+ lora_alpha=256,
319
+ lora_len=1225,
320
+ )
321
+ self.w2 = PLoRA(
322
+ self.intermediate_size,
323
+ self.hidden_size,
324
+ bias=False,
325
+ lora_r=256,
326
+ lora_alpha=256,
327
+ lora_len=1225,
328
+ )
329
+
330
+ self.act_fn = ACT2FN[config.hidden_act]
331
+
332
+ def forward(self, x, im_mask, infer_mode):
333
+ down_proj = self.w2(
334
+ self.act_fn(self.w1(x, im_mask, infer_mode))
335
+ * self.w3(x, im_mask, infer_mode),
336
+ im_mask,
337
+ infer_mode,
338
+ )
339
+
340
+ return down_proj
341
+
342
+
343
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
344
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
345
+ """
346
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
347
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
348
+ """
349
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
350
+ if n_rep == 1:
351
+ return hidden_states
352
+ hidden_states = hidden_states[:, :, None, :, :].expand(
353
+ batch, num_key_value_heads, n_rep, slen, head_dim
354
+ )
355
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
356
+
357
+
358
+ # Modified from transformers.model.llama.modeling_llama.LlamaAttention
359
+ class InternLM2Attention(nn.Module):
360
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
361
+
362
+ def __init__(self, config: InternLM2Config):
363
+ super().__init__()
364
+ self.config = config
365
+ self.hidden_size = config.hidden_size
366
+ self.num_heads = config.num_attention_heads
367
+ self.head_dim = self.hidden_size // self.num_heads
368
+ self.num_key_value_heads = config.num_key_value_heads
369
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
370
+ self.max_position_embeddings = config.max_position_embeddings
371
+ self.is_causal = True
372
+
373
+ if (self.head_dim * self.num_heads) != self.hidden_size:
374
+ raise ValueError(
375
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
376
+ f" and `num_heads`: {self.num_heads})."
377
+ )
378
+
379
+ # self.wqkv = nn.Linear(
380
+ self.wqkv = PLoRA(
381
+ self.hidden_size,
382
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
383
+ bias=config.bias,
384
+ lora_r=256,
385
+ lora_alpha=256,
386
+ lora_len=1225,
387
+ )
388
+
389
+ # self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
390
+ self.wo = PLoRA(
391
+ self.num_heads * self.head_dim,
392
+ self.hidden_size,
393
+ bias=config.bias,
394
+ lora_r=256,
395
+ lora_alpha=256,
396
+ lora_len=1225,
397
+ )
398
+ self._init_rope()
399
+
400
+ def _init_rope(self):
401
+ if self.config.rope_scaling is None:
402
+ self.rotary_emb = InternLM2RotaryEmbedding(
403
+ self.head_dim,
404
+ max_position_embeddings=self.max_position_embeddings,
405
+ base=self.config.rope_theta,
406
+ )
407
+ else:
408
+ scaling_type = self.config.rope_scaling["type"]
409
+ scaling_factor = self.config.rope_scaling["factor"]
410
+ if scaling_type == "dynamic":
411
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
412
+ self.head_dim,
413
+ max_position_embeddings=self.max_position_embeddings,
414
+ base=self.config.rope_theta,
415
+ scaling_factor=scaling_factor,
416
+ )
417
+ elif scaling_type == "linear":
418
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
419
+ self.head_dim,
420
+ max_position_embeddings=self.max_position_embeddings,
421
+ base=self.config.rope_theta,
422
+ scaling_factor=scaling_factor,
423
+ )
424
+ else:
425
+ raise ValueError(
426
+ "Currently we only support rotary embedding's type being 'dynamic' or 'linear'."
427
+ )
428
+ return self.rotary_emb
429
+
430
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
431
+ return (
432
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
433
+ .transpose(1, 2)
434
+ .contiguous()
435
+ )
436
+
437
+ def forward(
438
+ self,
439
+ hidden_states: torch.Tensor,
440
+ attention_mask: Optional[torch.Tensor] = None,
441
+ position_ids: Optional[torch.LongTensor] = None,
442
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
443
+ output_attentions: bool = False,
444
+ use_cache: bool = False,
445
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
446
+ infer_mode: str = "base",
447
+ **kwargs,
448
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
449
+ if "padding_mask" in kwargs:
450
+ warnings.warn(
451
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
452
+ "Please make sure use `attention_mask` instead.`"
453
+ )
454
+
455
+ bsz, q_len, _ = hidden_states.size()
456
+
457
+ qkv_states = self.wqkv(hidden_states, im_mask, infer_mode)
458
+
459
+ qkv_states = rearrange(
460
+ qkv_states,
461
+ "b q (h gs d) -> b q h gs d",
462
+ gs=2 + self.num_key_value_groups,
463
+ d=self.head_dim,
464
+ )
465
+
466
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
467
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
468
+ key_states = qkv_states[..., -2, :]
469
+ value_states = qkv_states[..., -1, :]
470
+
471
+ query_states = query_states.transpose(1, 2)
472
+ key_states = key_states.transpose(1, 2)
473
+ value_states = value_states.transpose(1, 2)
474
+
475
+ kv_seq_len = key_states.shape[-2]
476
+ if past_key_value is not None:
477
+ kv_seq_len += past_key_value[0].shape[-2]
478
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
479
+ query_states, key_states = apply_rotary_pos_emb(
480
+ query_states, key_states, cos, sin, position_ids
481
+ )
482
+
483
+ if past_key_value is not None:
484
+ # reuse k, v, self_attention
485
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
486
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
487
+
488
+ past_key_value = (key_states, value_states) if use_cache else None
489
+
490
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
491
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
492
+
493
+ attn_weights = torch.matmul(
494
+ query_states, key_states.transpose(2, 3)
495
+ ) / math.sqrt(self.head_dim)
496
+
497
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
498
+ raise ValueError(
499
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
500
+ f" {attn_weights.size()}"
501
+ )
502
+
503
+ if attention_mask is not None:
504
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
505
+ raise ValueError(
506
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
507
+ )
508
+ attn_weights = attn_weights + attention_mask
509
+
510
+ # upcast attention to fp32
511
+ attn_weights = nn.functional.softmax(
512
+ attn_weights, dim=-1, dtype=torch.float32
513
+ ).to(query_states.dtype)
514
+ attn_output = torch.matmul(attn_weights, value_states)
515
+
516
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
517
+ raise ValueError(
518
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
519
+ f" {attn_output.size()}"
520
+ )
521
+
522
+ attn_output = attn_output.transpose(1, 2).contiguous()
523
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
524
+
525
+ attn_output = self.wo(attn_output, im_mask, infer_mode)
526
+
527
+ if not output_attentions:
528
+ attn_weights = None
529
+
530
+ return attn_output, attn_weights, past_key_value
531
+
532
+
533
+ # Modified from transformers.model.llama.modeling_llama.InternLM2FlashAttention2
534
+ class InternLM2FlashAttention2(InternLM2Attention):
535
+ """
536
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
537
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
538
+ flash attention and deal with padding tokens in case the input contains any of them.
539
+ """
540
+
541
+ def forward(
542
+ self,
543
+ hidden_states: torch.Tensor,
544
+ attention_mask: Optional[torch.LongTensor] = None,
545
+ position_ids: Optional[torch.LongTensor] = None,
546
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
547
+ output_attentions: bool = False,
548
+ use_cache: bool = False,
549
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
550
+ infer_mode: str = "base",
551
+ **kwargs,
552
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
553
+ # InternLM2FlashAttention2 attention does not support output_attentions
554
+ if "padding_mask" in kwargs:
555
+ warnings.warn(
556
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
557
+ "Please make sure use `attention_mask` instead.`"
558
+ )
559
+
560
+ # overwrite attention_mask with padding_mask
561
+ attention_mask = kwargs.pop("padding_mask")
562
+
563
+ output_attentions = False
564
+
565
+ bsz, q_len, _ = hidden_states.size()
566
+
567
+ qkv_states = self.wqkv(hidden_states, im_mask, infer_mode)
568
+
569
+ qkv_states = rearrange(
570
+ qkv_states,
571
+ "b q (h gs d) -> b q h gs d",
572
+ gs=2 + self.num_key_value_groups,
573
+ d=self.head_dim,
574
+ )
575
+
576
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
577
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
578
+ key_states = qkv_states[..., -2, :]
579
+ value_states = qkv_states[..., -1, :]
580
+
581
+ query_states = query_states.transpose(1, 2)
582
+ key_states = key_states.transpose(1, 2)
583
+ value_states = value_states.transpose(1, 2)
584
+
585
+ kv_seq_len = key_states.shape[-2]
586
+ if past_key_value is not None:
587
+ kv_seq_len += past_key_value[0].shape[-2]
588
+
589
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
590
+
591
+ query_states, key_states = apply_rotary_pos_emb(
592
+ query_states, key_states, cos, sin, position_ids
593
+ )
594
+
595
+ if past_key_value is not None:
596
+ # reuse k, v, self_attention
597
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
598
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
599
+
600
+ past_key_value = (key_states, value_states) if use_cache else None
601
+
602
+ query_states = query_states.transpose(1, 2)
603
+ key_states = key_states.transpose(1, 2)
604
+ value_states = value_states.transpose(1, 2)
605
+
606
+ attn_output = self._flash_attention_forward(
607
+ query_states, key_states, value_states, attention_mask, q_len
608
+ )
609
+
610
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
611
+ attn_output = self.wo(attn_output, im_mask, infer_mode)
612
+
613
+ if not output_attentions:
614
+ attn_weights = None
615
+
616
+ return attn_output, attn_weights, past_key_value
617
+
618
+ def _flash_attention_forward(
619
+ self,
620
+ query_states,
621
+ key_states,
622
+ value_states,
623
+ attention_mask,
624
+ query_length,
625
+ dropout=0.0,
626
+ softmax_scale=None,
627
+ ):
628
+ """
629
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
630
+ first unpad the input, then computes the attention scores and pad the final attention scores.
631
+
632
+ Args:
633
+ query_states (`torch.Tensor`):
634
+ Input query states to be passed to Flash Attention API
635
+ key_states (`torch.Tensor`):
636
+ Input key states to be passed to Flash Attention API
637
+ value_states (`torch.Tensor`):
638
+ Input value states to be passed to Flash Attention API
639
+ attention_mask (`torch.Tensor`):
640
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
641
+ position of padding tokens and 1 for the position of non-padding tokens.
642
+ dropout (`int`, *optional*):
643
+ Attention dropout
644
+ softmax_scale (`float`, *optional*):
645
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
646
+ """
647
+ # Contains at least one padding token in the sequence
648
+ causal = self.is_causal and query_length != 1
649
+ if attention_mask is not None:
650
+ batch_size = query_states.shape[0]
651
+ (
652
+ query_states,
653
+ key_states,
654
+ value_states,
655
+ indices_q,
656
+ cu_seq_lens,
657
+ max_seq_lens,
658
+ ) = self._unpad_input(
659
+ query_states, key_states, value_states, attention_mask, query_length
660
+ )
661
+
662
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
663
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
664
+
665
+ attn_output_unpad = flash_attn_varlen_func(
666
+ query_states,
667
+ key_states,
668
+ value_states,
669
+ cu_seqlens_q=cu_seqlens_q,
670
+ cu_seqlens_k=cu_seqlens_k,
671
+ max_seqlen_q=max_seqlen_in_batch_q,
672
+ max_seqlen_k=max_seqlen_in_batch_k,
673
+ dropout_p=dropout,
674
+ softmax_scale=softmax_scale,
675
+ causal=causal,
676
+ )
677
+
678
+ attn_output = pad_input(
679
+ attn_output_unpad, indices_q, batch_size, query_length
680
+ )
681
+ else:
682
+ attn_output = flash_attn_func(
683
+ query_states,
684
+ key_states,
685
+ value_states,
686
+ dropout,
687
+ softmax_scale=softmax_scale,
688
+ causal=causal,
689
+ )
690
+
691
+ return attn_output
692
+
693
+ def _unpad_input(
694
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
695
+ ):
696
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
697
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
698
+
699
+ key_layer = index_first_axis(
700
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
701
+ indices_k,
702
+ )
703
+ value_layer = index_first_axis(
704
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
705
+ indices_k,
706
+ )
707
+
708
+ if query_length == kv_seq_len:
709
+ query_layer = index_first_axis(
710
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
711
+ indices_k,
712
+ )
713
+ cu_seqlens_q = cu_seqlens_k
714
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
715
+ indices_q = indices_k
716
+ elif query_length == 1:
717
+ max_seqlen_in_batch_q = 1
718
+ cu_seqlens_q = torch.arange(
719
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
720
+ ) # There is a memcpy here, that is very bad.
721
+ indices_q = cu_seqlens_q[:-1]
722
+ query_layer = query_layer.squeeze(1)
723
+ else:
724
+ # The -q_len: slice assumes left padding.
725
+ attention_mask = attention_mask[:, -query_length:]
726
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
727
+ query_layer, attention_mask
728
+ )
729
+
730
+ return (
731
+ query_layer,
732
+ key_layer,
733
+ value_layer,
734
+ indices_q.to(torch.int64),
735
+ (cu_seqlens_q, cu_seqlens_k),
736
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
737
+ )
738
+
739
+
740
+ INTERNLM2_ATTENTION_CLASSES = {
741
+ "eager": InternLM2Attention,
742
+ "flash_attention_2": InternLM2FlashAttention2,
743
+ }
744
+
745
+
746
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
747
+ class InternLM2DecoderLayer(nn.Module):
748
+ def __init__(self, config: InternLM2Config):
749
+ super().__init__()
750
+ self.hidden_size = config.hidden_size
751
+
752
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](
753
+ config=config
754
+ )
755
+
756
+ self.feed_forward = InternLM2MLP(config)
757
+ self.attention_norm = InternLM2RMSNorm(
758
+ config.hidden_size, eps=config.rms_norm_eps
759
+ )
760
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
761
+
762
+ def forward(
763
+ self,
764
+ hidden_states: torch.Tensor,
765
+ attention_mask: Optional[torch.Tensor] = None,
766
+ position_ids: Optional[torch.LongTensor] = None,
767
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
768
+ output_attentions: Optional[bool] = False,
769
+ use_cache: Optional[bool] = False,
770
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
771
+ infer_mode: str = "base",
772
+ **kwargs,
773
+ ) -> Tuple[
774
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
775
+ ]:
776
+ """
777
+ Args:
778
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
779
+ attention_mask (`torch.FloatTensor`, *optional*):
780
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
781
+ query_sequence_length, key_sequence_length)` if default attention is used.
782
+ output_attentions (`bool`, *optional*):
783
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
784
+ returned tensors for more detail.
785
+ use_cache (`bool`, *optional*):
786
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
787
+ (see `past_key_values`).
788
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
789
+ """
790
+ if "padding_mask" in kwargs:
791
+ warnings.warn(
792
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
793
+ "Please make sure use `attention_mask` instead.`"
794
+ )
795
+
796
+ residual = hidden_states
797
+
798
+ hidden_states = self.attention_norm(hidden_states)
799
+
800
+ # Self Attention
801
+ hidden_states, self_attn_weights, present_key_value = self.attention(
802
+ hidden_states=hidden_states,
803
+ attention_mask=attention_mask,
804
+ position_ids=position_ids,
805
+ past_key_value=past_key_value,
806
+ output_attentions=output_attentions,
807
+ use_cache=use_cache,
808
+ im_mask=im_mask,
809
+ infer_mode=infer_mode,
810
+ **kwargs,
811
+ )
812
+ hidden_states = residual + hidden_states
813
+
814
+ # Fully Connected
815
+ residual = hidden_states
816
+ hidden_states = self.ffn_norm(hidden_states)
817
+ hidden_states = self.feed_forward(hidden_states, im_mask, infer_mode)
818
+ hidden_states = residual + hidden_states
819
+
820
+ outputs = (hidden_states,)
821
+
822
+ if output_attentions:
823
+ outputs += (self_attn_weights,)
824
+
825
+ if use_cache:
826
+ outputs += (present_key_value,)
827
+
828
+ return outputs
829
+
830
+
831
+ InternLM2_START_DOCSTRING = r"""
832
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
833
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
834
+ etc.)
835
+
836
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
837
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
838
+ and behavior.
839
+
840
+ Parameters:
841
+ config ([`InternLM2Config`]):
842
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
843
+ load the weights associated with the model, only the configuration. Check out the
844
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
845
+ """
846
+
847
+
848
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
849
+ @add_start_docstrings(
850
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
851
+ InternLM2_START_DOCSTRING,
852
+ )
853
+ class InternLM2PreTrainedModel(PreTrainedModel):
854
+ config_class = InternLM2Config
855
+ base_model_prefix = "model"
856
+ supports_gradient_checkpointing = True
857
+ _no_split_modules = ["InternLM2DecoderLayer"]
858
+ _skip_keys_device_placement = "past_key_values"
859
+
860
+ def _init_weights(self, module):
861
+ std = self.config.initializer_range
862
+ if isinstance(module, nn.Linear):
863
+ module.weight.data.normal_(mean=0.0, std=std)
864
+ if module.bias is not None:
865
+ module.bias.data.zero_()
866
+ elif isinstance(module, nn.Embedding):
867
+ module.weight.data.normal_(mean=0.0, std=std)
868
+ if module.padding_idx is not None:
869
+ module.weight.data[module.padding_idx].zero_()
870
+
871
+
872
+ InternLM2_INPUTS_DOCSTRING = r"""
873
+ Args:
874
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
875
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
876
+ it.
877
+
878
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
879
+ [`PreTrainedTokenizer.__call__`] for details.
880
+
881
+ [What are input IDs?](../glossary#input-ids)
882
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
883
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
884
+
885
+ - 1 for tokens that are **not masked**,
886
+ - 0 for tokens that are **masked**.
887
+
888
+ [What are attention masks?](../glossary#attention-mask)
889
+
890
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
891
+ [`PreTrainedTokenizer.__call__`] for details.
892
+
893
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
894
+ `past_key_values`).
895
+
896
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
897
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
898
+ information on the default strategy.
899
+
900
+ - 1 indicates the head is **not masked**,
901
+ - 0 indicates the head is **masked**.
902
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
903
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
904
+ config.n_positions - 1]`.
905
+
906
+ [What are position IDs?](../glossary#position-ids)
907
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
908
+ when `config.use_cache=True`):
909
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
910
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
911
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
912
+
913
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
914
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
915
+
916
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
917
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
918
+ of shape `(batch_size, sequence_length)`.
919
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
920
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
921
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
922
+ model's internal embedding lookup matrix.
923
+ use_cache (`bool`, *optional*):
924
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
925
+ `past_key_values`).
926
+ output_attentions (`bool`, *optional*):
927
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
928
+ tensors for more detail.
929
+ output_hidden_states (`bool`, *optional*):
930
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
931
+ more detail.
932
+ return_dict (`bool`, *optional*):
933
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
934
+ """
935
+
936
+
937
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
938
+ @add_start_docstrings(
939
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
940
+ InternLM2_START_DOCSTRING,
941
+ )
942
+ class InternLM2Model(InternLM2PreTrainedModel):
943
+ """
944
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
945
+
946
+ Args:
947
+ config: InternLM2Config
948
+ """
949
+
950
+ _auto_class = "AutoModel"
951
+
952
+ def __init__(self, config: InternLM2Config):
953
+ super().__init__(config)
954
+ self.padding_idx = config.pad_token_id
955
+ self.vocab_size = config.vocab_size
956
+ self.config = config
957
+
958
+ self.tok_embeddings = nn.Embedding(
959
+ config.vocab_size, config.hidden_size, self.padding_idx
960
+ )
961
+
962
+ self.layers = nn.ModuleList(
963
+ [InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)]
964
+ )
965
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
966
+
967
+ self.gradient_checkpointing = False
968
+ # Initialize weights and apply final processing
969
+ self.post_init()
970
+
971
+ def get_input_embeddings(self):
972
+ return self.tok_embeddings
973
+
974
+ def set_input_embeddings(self, value):
975
+ self.tok_embeddings = value
976
+
977
+ def _prepare_decoder_attention_mask(
978
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
979
+ ):
980
+ # create causal mask
981
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
982
+ combined_attention_mask = None
983
+ if input_shape[-1] > 1:
984
+ combined_attention_mask = _make_causal_mask(
985
+ input_shape,
986
+ inputs_embeds.dtype,
987
+ device=inputs_embeds.device,
988
+ past_key_values_length=past_key_values_length,
989
+ )
990
+
991
+ if attention_mask is not None:
992
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
993
+ expanded_attn_mask = _expand_mask(
994
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
995
+ ).to(inputs_embeds.device)
996
+ combined_attention_mask = (
997
+ expanded_attn_mask
998
+ if combined_attention_mask is None
999
+ else expanded_attn_mask + combined_attention_mask
1000
+ )
1001
+
1002
+ return combined_attention_mask
1003
+
1004
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1005
+ def forward(
1006
+ self,
1007
+ input_ids: torch.LongTensor = None,
1008
+ attention_mask: Optional[torch.Tensor] = None,
1009
+ position_ids: Optional[torch.LongTensor] = None,
1010
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1011
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1012
+ use_cache: Optional[bool] = None,
1013
+ output_attentions: Optional[bool] = None,
1014
+ output_hidden_states: Optional[bool] = None,
1015
+ return_dict: Optional[bool] = None,
1016
+ **kwargs,
1017
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1018
+ im_mask = kwargs.get("im_mask", None)
1019
+ infer_mode = kwargs.get("infer_mode", "base")
1020
+
1021
+ output_attentions = (
1022
+ output_attentions
1023
+ if output_attentions is not None
1024
+ else self.config.output_attentions
1025
+ )
1026
+ output_hidden_states = (
1027
+ output_hidden_states
1028
+ if output_hidden_states is not None
1029
+ else self.config.output_hidden_states
1030
+ )
1031
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1032
+
1033
+ return_dict = (
1034
+ return_dict if return_dict is not None else self.config.use_return_dict
1035
+ )
1036
+
1037
+ if self.config.attn_implementation == "flash_attention_2":
1038
+ _import_flash_attn()
1039
+
1040
+ # retrieve input_ids and inputs_embeds
1041
+ if input_ids is not None and inputs_embeds is not None:
1042
+ raise ValueError(
1043
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1044
+ )
1045
+ elif input_ids is not None:
1046
+ batch_size, seq_length = input_ids.shape[:2]
1047
+ elif inputs_embeds is not None:
1048
+ batch_size, seq_length = inputs_embeds.shape[:2]
1049
+ else:
1050
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1051
+
1052
+ seq_length_with_past = seq_length
1053
+ past_key_values_length = 0
1054
+ if past_key_values is not None:
1055
+ past_key_values_length = past_key_values[0][0].shape[2]
1056
+ seq_length_with_past = seq_length_with_past + past_key_values_length
1057
+
1058
+ if position_ids is None:
1059
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1060
+ position_ids = torch.arange(
1061
+ past_key_values_length,
1062
+ seq_length + past_key_values_length,
1063
+ dtype=torch.long,
1064
+ device=device,
1065
+ )
1066
+ position_ids = position_ids.unsqueeze(0)
1067
+
1068
+ if inputs_embeds is None:
1069
+ inputs_embeds = self.tok_embeddings(input_ids)
1070
+ im_mask = (
1071
+ torch.zeros(inputs_embeds.shape[:2]).to(inputs_embeds.device).bool()
1072
+ )
1073
+
1074
+ if self.config.attn_implementation == "flash_attention_2":
1075
+ # 2d mask is passed through the layers
1076
+ attention_mask = (
1077
+ attention_mask
1078
+ if (attention_mask is not None and 0 in attention_mask)
1079
+ else None
1080
+ )
1081
+ else:
1082
+ if attention_mask is None:
1083
+ attention_mask = torch.ones(
1084
+ (batch_size, seq_length_with_past),
1085
+ dtype=torch.bool,
1086
+ device=inputs_embeds.device,
1087
+ )
1088
+ attention_mask = self._prepare_decoder_attention_mask(
1089
+ attention_mask,
1090
+ (batch_size, seq_length),
1091
+ inputs_embeds,
1092
+ past_key_values_length,
1093
+ )
1094
+
1095
+ # embed positions
1096
+ hidden_states = inputs_embeds
1097
+
1098
+ if self.gradient_checkpointing and self.training:
1099
+ if use_cache:
1100
+ logger.warning_once(
1101
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1102
+ )
1103
+ use_cache = False
1104
+
1105
+ # decoder layers
1106
+ all_hidden_states = () if output_hidden_states else None
1107
+ all_self_attns = () if output_attentions else None
1108
+ next_decoder_cache = () if use_cache else None
1109
+
1110
+ for idx, decoder_layer in enumerate(self.layers):
1111
+ if output_hidden_states:
1112
+ all_hidden_states += (hidden_states,)
1113
+
1114
+ past_key_value = (
1115
+ past_key_values[idx] if past_key_values is not None else None
1116
+ )
1117
+
1118
+ if self.gradient_checkpointing and self.training:
1119
+
1120
+ def create_custom_forward(module):
1121
+ def custom_forward(*inputs):
1122
+ # None for past_key_value
1123
+ return module(
1124
+ *inputs, output_attentions, None, im_mask, infer_mode
1125
+ )
1126
+
1127
+ return custom_forward
1128
+
1129
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1130
+ create_custom_forward(decoder_layer),
1131
+ hidden_states,
1132
+ attention_mask,
1133
+ position_ids,
1134
+ None,
1135
+ )
1136
+ else:
1137
+ layer_outputs = decoder_layer(
1138
+ hidden_states,
1139
+ attention_mask=attention_mask,
1140
+ position_ids=position_ids,
1141
+ past_key_value=past_key_value,
1142
+ output_attentions=output_attentions,
1143
+ use_cache=use_cache,
1144
+ im_mask=im_mask,
1145
+ infer_mode=infer_mode,
1146
+ )
1147
+
1148
+ hidden_states = layer_outputs[0]
1149
+
1150
+ if use_cache:
1151
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
1152
+
1153
+ if output_attentions:
1154
+ all_self_attns += (layer_outputs[1],)
1155
+
1156
+ hidden_states = self.norm(hidden_states)
1157
+
1158
+ # add hidden states from the last decoder layer
1159
+ if output_hidden_states:
1160
+ all_hidden_states += (hidden_states,)
1161
+
1162
+ next_cache = next_decoder_cache if use_cache else None
1163
+ if not return_dict:
1164
+ return tuple(
1165
+ v
1166
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1167
+ if v is not None
1168
+ )
1169
+ return BaseModelOutputWithPast(
1170
+ last_hidden_state=hidden_states,
1171
+ past_key_values=next_cache,
1172
+ hidden_states=all_hidden_states,
1173
+ attentions=all_self_attns,
1174
+ )
modeling_internlm_xcomposer2.py ADDED
@@ -0,0 +1,997 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/modeling_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """PyTorch InternLMXComposer2 model."""
18
+
19
+ import copy
20
+ import os
21
+ import random
22
+ import re
23
+ from pathlib import Path
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import numpy as np
27
+ import torch
28
+ import torch.utils.checkpoint
29
+ from PIL import Image
30
+ from torch import nn
31
+ from torch.nn import CrossEntropyLoss
32
+ from torchvision import transforms
33
+ from transformers import (
34
+ StoppingCriteria,
35
+ StoppingCriteriaList,
36
+ set_seed,
37
+ )
38
+ from transformers.generation.streamers import BaseStreamer
39
+ from transformers.modeling_outputs import CausalLMOutputWithPast
40
+ from transformers.utils import (
41
+ add_start_docstrings_to_model_forward,
42
+ replace_return_docstrings,
43
+ )
44
+
45
+ from .build_mlp import build_vision_projector, build_vision_tower
46
+ from .ixc_utils import Image_transform, Video_transform, frame2img, get_font, load_video
47
+ from .modeling_internlm2 import (
48
+ InternLM2_INPUTS_DOCSTRING,
49
+ InternLM2Config,
50
+ InternLM2Model,
51
+ InternLM2PreTrainedModel,
52
+ )
53
+
54
+ _CONFIG_FOR_DOC = "InternLMXcomposer2Config"
55
+
56
+ image_extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}
57
+ video_extensions = {".mp4", ".avi", ".mkv", ".mov", ".wmv"}
58
+
59
+
60
+ class StoppingCriteriaSub(StoppingCriteria):
61
+ def __init__(self, stops=[], encounters=1):
62
+ super().__init__()
63
+ self.stops = stops
64
+
65
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor):
66
+ for stop in self.stops:
67
+ if torch.all((stop == input_ids[0][-len(stop) :])).item():
68
+ return True
69
+ return False
70
+
71
+
72
+ def get_stopping_criteria(stop_words_ids):
73
+ stop_words_ids = [torch.tensor([i]).cuda() for i in stop_words_ids]
74
+ stopping_criteria = StoppingCriteriaList(
75
+ [StoppingCriteriaSub(stops=stop_words_ids)]
76
+ )
77
+ return stopping_criteria
78
+
79
+
80
+ def set_random_seed(seed, set_cudnn=False):
81
+ """Set the random seed for reproducibility.
82
+
83
+ Parameters:
84
+ seed (int): The seed to use for generating random numbers.
85
+ """
86
+ torch.manual_seed(seed)
87
+ if torch.cuda.is_available():
88
+ torch.cuda.manual_seed_all(seed) # For multi-GPU.
89
+ np.random.seed(seed)
90
+ random.seed(seed)
91
+ if set_cudnn and torch.backends.cudnn.is_available():
92
+ torch.backends.cudnn.deterministic = True
93
+ torch.backends.cudnn.benchmark = False
94
+
95
+
96
+ class InternLMXComposer2ForCausalLM(InternLM2PreTrainedModel):
97
+ _auto_class = "AutoModelForCausalLM"
98
+
99
+ _tied_weights_keys = ["output.weight"]
100
+
101
+ def __init__(self, config: InternLM2Config):
102
+ super().__init__(config)
103
+ self.model = InternLM2Model(config)
104
+ self.vocab_size = config.vocab_size
105
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
106
+ self.tokenizer = None
107
+ self.hd_num = 25
108
+ self.font = get_font()
109
+
110
+ self.max_length = config.max_length
111
+ print(f"Set max length to {self.max_length}")
112
+ # Initialize weights and apply final processing
113
+ self.post_init()
114
+ self.plora_glb_GN = nn.Parameter(torch.zeros([1, 1, 4096]))
115
+ self.plora_sub_GN = nn.Parameter(torch.zeros([1, 1, 1, 4096]))
116
+
117
+ self.vit = build_vision_tower()
118
+ self.vision_proj = build_vision_projector()
119
+
120
+ self.vis_processor = transforms.Compose(
121
+ [
122
+ transforms.ToTensor(),
123
+ transforms.Normalize(
124
+ (0.48145466, 0.4578275, 0.40821073),
125
+ (0.26862954, 0.26130258, 0.27577711),
126
+ ),
127
+ ]
128
+ )
129
+
130
+ def _set_gradient_checkpointing(self, module, value=False):
131
+ if isinstance(module, InternLM2Model):
132
+ module.gradient_checkpointing = value
133
+ if value:
134
+ self.vit.vision_tower.vision_model.encoder.gradient_checkpointing = value
135
+
136
+ def get_input_embeddings(self):
137
+ return self.model.tok_embeddings
138
+
139
+ def set_input_embeddings(self, value):
140
+ self.model.tok_embeddings = value
141
+
142
+ def get_output_embeddings(self):
143
+ return self.output
144
+
145
+ def set_output_embeddings(self, new_embeddings):
146
+ self.output = new_embeddings
147
+
148
+ def set_decoder(self, decoder):
149
+ self.model = decoder
150
+
151
+ def get_decoder(self):
152
+ return self.model
153
+
154
+ def encode_text(self, text, add_special_tokens=False):
155
+ token = self.tokenizer(
156
+ text, return_tensors="pt", add_special_tokens=add_special_tokens
157
+ ).input_ids.to(self.device) # type: ignore
158
+ embs = self.model.tok_embeddings(token)
159
+ return embs
160
+
161
+ def encode_img(
162
+ self, image: torch.Tensor | str | Path, hd_num: int = 25
163
+ ) -> torch.Tensor:
164
+ if image is None:
165
+ return None # UNREACHABLE # type: ignore
166
+ if isinstance(image, str):
167
+ _, ext = os.path.splitext(image)
168
+ if ext.lower() in image_extensions:
169
+ image_pil = Image.open(image)
170
+ image_pt = Image_transform(image_pil, hd_num=hd_num)
171
+ elif ext.lower() in video_extensions:
172
+ image_pil_list = load_video(image)
173
+ image_pil_list = frame2img(image_pil_list, self.font)
174
+ image_pt = Video_transform(image_pil_list, hd_num=hd_num)
175
+ else:
176
+ print("Unknow input format", image)
177
+ return None # UNREACHABLE # type: ignore
178
+ image = self.vis_processor(image_pt).unsqueeze(0).to(self.device)
179
+ else:
180
+ assert isinstance(image, torch.Tensor)
181
+
182
+ img_embeds, atts_img, img_target = self.img2emb(image)
183
+ return img_embeds
184
+
185
+ def img2emb(self, image):
186
+ img_embeds, img_split = self.vit([image], self.plora_glb_GN, self.plora_sub_GN)
187
+ if len(img_split) > 1:
188
+ print("Batch Size >1 is not supported.")
189
+ assert 0
190
+ # print (img_embeds.shape)
191
+ img_embeds = self.vision_proj(img_embeds)
192
+ atts_img = torch.ones(img_embeds.size()[:-1], dtype=torch.long).to(
193
+ img_embeds.device
194
+ )
195
+
196
+ img_target = (
197
+ torch.ones(img_embeds.size()[:2], dtype=torch.long).to(img_embeds.device)
198
+ * -100
199
+ )
200
+
201
+ return img_embeds, atts_img, img_target
202
+
203
+ def prompt_wrap(self, img_embeds, prompt):
204
+ batch_size = img_embeds.shape[0]
205
+ p_before, p_after = prompt.split("<ImageHere>")
206
+ p_before_tokens = self.tokenizer(
207
+ p_before, return_tensors="pt", add_special_tokens=True
208
+ ).to(img_embeds.device) # type: ignore
209
+
210
+ p_before_embeds = self.model.tok_embeddings(p_before_tokens.input_ids).expand(
211
+ batch_size, -1, -1
212
+ )
213
+ wrapped_img_embeds = torch.cat([p_before_embeds, img_embeds], dim=1)
214
+
215
+ wrapped_atts_img = torch.ones(
216
+ wrapped_img_embeds.size()[:-1], dtype=torch.long
217
+ ).to(img_embeds.device)
218
+
219
+ wrapped_target = (
220
+ torch.ones(batch_size, wrapped_img_embeds.shape[1], dtype=torch.long).to(
221
+ img_embeds.device
222
+ )
223
+ * -100
224
+ )
225
+
226
+ return wrapped_img_embeds, wrapped_atts_img, wrapped_target
227
+
228
+ def text2emb(self, text, add_special_tokens=False):
229
+ to_regress_tokens = self.tokenizer(
230
+ text,
231
+ return_tensors="pt",
232
+ padding="longest",
233
+ truncation=True,
234
+ max_length=self.max_length,
235
+ add_special_tokens=add_special_tokens,
236
+ ).to(self.device) # type: ignore
237
+
238
+ targets = self.mask_human_targets(to_regress_tokens.input_ids)
239
+ targets = targets.to(self.device)
240
+ return to_regress_tokens, targets
241
+
242
+ def interleav_wrap_chat(
243
+ self, query, image, history=[], meta_instruction="", max_length=16384, hd_num=24
244
+ ):
245
+ self.max_length = max_length
246
+ prompt = ""
247
+ if meta_instruction:
248
+ prompt += (
249
+ f"""[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
250
+ )
251
+ for record in history:
252
+ prompt += f"""[UNUSED_TOKEN_146]user\n{record[0]}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n{record[1]}[UNUSED_TOKEN_145]\n"""
253
+ prompt += f"""[UNUSED_TOKEN_146]user\n{query}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n"""
254
+
255
+ image_nums = len(image)
256
+ if image_nums == 1 and prompt.find("<ImageHere>") == -1:
257
+ # print ('auto append image at the begining')
258
+ prompt = "<ImageHere>" + prompt
259
+
260
+ parts = prompt.split("<ImageHere>")
261
+ wrap_embeds, wrap_im_mask = [], []
262
+ temp_len = 0
263
+ need_bos = True
264
+
265
+ if len(parts) != image_nums + 1:
266
+ # raise ValueError('Invalid <ImageHere> prompt format.')
267
+ print("Waring! The image number != given position!")
268
+ if image_nums > 1:
269
+ hd_num = 6
270
+
271
+ for idx, part in enumerate(parts):
272
+ if need_bos or len(part) > 0:
273
+ part_tokens = self.tokenizer(
274
+ part,
275
+ return_tensors="pt",
276
+ padding="longest",
277
+ add_special_tokens=need_bos,
278
+ ).to(self.device) # type: ignore
279
+ if need_bos:
280
+ need_bos = False
281
+
282
+ part_embeds = self.model.tok_embeddings(part_tokens.input_ids)
283
+ wrap_embeds.append(part_embeds)
284
+ wrap_im_mask.append(torch.zeros(part_embeds.shape[:2]))
285
+ temp_len += part_embeds.shape[1]
286
+ if idx < image_nums:
287
+ img = self.encode_img(image[idx], hd_num)
288
+ wrap_embeds.append(img)
289
+ wrap_im_mask.append(torch.ones(img.shape[:2]))
290
+ temp_len += img.shape[1]
291
+
292
+ if temp_len > self.max_length:
293
+ break
294
+
295
+ wrap_embeds = torch.cat(wrap_embeds, dim=1)
296
+ wrap_im_mask = torch.cat(wrap_im_mask, dim=1)
297
+ wrap_embeds = wrap_embeds[:, : self.max_length].to(self.device)
298
+ wrap_im_mask = wrap_im_mask[:, : self.max_length].to(self.device).bool()
299
+ inputs = {"inputs_embeds": wrap_embeds}
300
+ return inputs, wrap_im_mask, temp_len
301
+
302
+ def interleav_wrap(self, img_list: list[torch.Tensor], text_list, image_nums):
303
+ temp_embeds = []
304
+ temp_im_mask = []
305
+ temp_tars = []
306
+
307
+ # encode_image
308
+ if len(img_list) > 0:
309
+ img_embeds, img_split = self.vit(
310
+ img_list, self.plora_glb_GN, self.plora_sub_GN
311
+ )
312
+ img_embeds = self.vision_proj(img_embeds)
313
+ else:
314
+ img_embeds = None
315
+ img_split = []
316
+
317
+ text_list = text_list[0]
318
+ for idx, text in enumerate(text_list):
319
+ image_num = image_nums[idx]
320
+ im_id = int(np.sum(image_nums[:idx]))
321
+ images = []
322
+ for i in range(image_nums[idx]):
323
+ st = int(np.sum(img_split[: im_id + i]))
324
+ sp = img_split[im_id + i]
325
+ temp_img = img_embeds[:, st : st + sp] # type: ignore
326
+ images.append(temp_img)
327
+
328
+ if image_num == 1 and text.find("<ImageHere>") == -1:
329
+ text = "<ImageHere>" + text
330
+ parts = text.split("<ImageHere>")
331
+
332
+ wrap_tokens, wrap_embeds, wrap_im_mask = [], [], []
333
+ temp_len = 0
334
+ need_bos = True
335
+ for idx, part in enumerate(parts):
336
+ if len(part) > 0:
337
+ part_tokens = self.tokenizer(
338
+ part,
339
+ return_tensors="pt",
340
+ padding="longest",
341
+ add_special_tokens=need_bos,
342
+ ).to(self.device) # type: ignore
343
+ if need_bos:
344
+ need_bos = False
345
+ wrap_tokens.append(part_tokens.input_ids)
346
+ part_embeds = self.model.tok_embeddings(part_tokens.input_ids)
347
+ wrap_embeds.append(part_embeds)
348
+ wrap_im_mask.append(
349
+ torch.zeros(part_embeds.shape[:2]).to(self.device)
350
+ )
351
+ temp_len += part_embeds.shape[1]
352
+ if idx < image_num:
353
+ wrap_embeds.append(images[idx])
354
+ wrap_token = (
355
+ torch.ones(images[idx].shape[:2], dtype=torch.long).to(
356
+ self.device
357
+ )
358
+ * -100
359
+ )
360
+ wrap_tokens.append(wrap_token)
361
+ wrap_im_mask.append(
362
+ torch.ones(images[idx].shape[:2]).to(self.device)
363
+ )
364
+ temp_len += images[idx].shape[1]
365
+ if temp_len > self.max_length:
366
+ break
367
+ wrap_tokens = torch.cat(wrap_tokens, dim=1)
368
+ wrap_embeds = torch.cat(wrap_embeds, dim=1)
369
+ wrap_im_mask = torch.cat(wrap_im_mask, dim=1)
370
+
371
+ wrap_target = self.mask_human_targets(wrap_tokens).to(self.device)
372
+
373
+ temp_embeds.append(wrap_embeds)
374
+ temp_im_mask.append(wrap_im_mask)
375
+ temp_tars.append(wrap_target)
376
+
377
+ temp_max_len = np.max([i.shape[1] for i in temp_embeds])
378
+ temp_max_len = min(temp_max_len, self.max_length)
379
+
380
+ final_input, final_atts, final_tars, final_mask = [], [], [], []
381
+ pad = torch.ones([1, 1]) * self.tokenizer.pad_token_id # type: ignore
382
+ pad = pad.long().to(self.device)
383
+ pad_emb = self.model.tok_embeddings(pad)
384
+
385
+ for idx in range(len(temp_embeds)):
386
+ temp_len = temp_embeds[idx].shape[1]
387
+ if temp_len >= temp_max_len:
388
+ final_input.append(temp_embeds[idx][:, :temp_max_len])
389
+ final_atts.append(
390
+ torch.ones(1, temp_max_len).to(wrap_target.dtype).to(self.device)
391
+ )
392
+ final_tars.append(temp_tars[idx][:, :temp_max_len])
393
+ final_mask.append(temp_im_mask[idx][:, :temp_max_len])
394
+ else:
395
+ final_input.append(
396
+ torch.cat(
397
+ [
398
+ temp_embeds[idx],
399
+ pad_emb.repeat(1, temp_max_len - temp_len, 1),
400
+ ],
401
+ dim=1,
402
+ )
403
+ )
404
+ final_atts.append(
405
+ torch.cat(
406
+ [
407
+ torch.ones(1, temp_len),
408
+ torch.zeros(1, temp_max_len - temp_len),
409
+ ],
410
+ dim=1,
411
+ )
412
+ .to(wrap_target.dtype)
413
+ .to(self.device)
414
+ )
415
+ final_tars.append(
416
+ torch.cat(
417
+ [
418
+ temp_tars[idx],
419
+ (torch.ones(1, temp_max_len - temp_len) * -100)
420
+ .to(wrap_target.dtype)
421
+ .to(self.device),
422
+ ],
423
+ dim=1,
424
+ )
425
+ )
426
+ final_mask.append(
427
+ torch.cat(
428
+ [
429
+ temp_im_mask[idx],
430
+ (torch.zeros(1, temp_max_len - temp_len))
431
+ .to(wrap_target.dtype)
432
+ .to(self.device),
433
+ ],
434
+ dim=1,
435
+ )
436
+ )
437
+
438
+ inputs_embeds = torch.cat(final_input, dim=0)
439
+ attention_mask = torch.cat(final_atts, dim=0)
440
+ targets = torch.cat(final_tars, dim=0)
441
+ im_mask = torch.cat(final_mask, dim=0)
442
+
443
+ return inputs_embeds, attention_mask, targets, im_mask
444
+
445
+ def mask_human_targets(self, input_ids, pure=False):
446
+ target_batch = []
447
+ for bs in range(input_ids.shape[0]):
448
+ ids = input_ids[bs]
449
+ targets = copy.deepcopy(ids)
450
+ end_count = 0
451
+ last_eoa = 0
452
+ for i, temp_id in enumerate(ids):
453
+ if temp_id == 92542:
454
+ if end_count % 2 == 0:
455
+ targets[last_eoa : i + 6] = -100
456
+ else:
457
+ last_eoa = i + 1
458
+ end_count += 1
459
+ # # eos and following pad
460
+ elif temp_id == 2:
461
+ # loss on eos, but not on pad
462
+ targets[i + 1 :] = -100
463
+ break
464
+ # trunction, end at last question
465
+ if temp_id != 2 and end_count % 2 == 0:
466
+ # mask all after the last answer
467
+ targets[last_eoa + 1 :] = -100
468
+ target_batch.append(targets.unsqueeze(0))
469
+ target_batch = torch.cat(target_batch, dim=0)
470
+ return target_batch
471
+
472
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
473
+ @replace_return_docstrings(
474
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
475
+ )
476
+ def forward(
477
+ self,
478
+ input_ids: torch.LongTensor | None = None,
479
+ attention_mask: Optional[torch.Tensor] | None = None,
480
+ position_ids: Optional[torch.LongTensor] | None = None,
481
+ past_key_values: Optional[List[torch.FloatTensor]] | None = None,
482
+ inputs_embeds: Optional[torch.FloatTensor] | None = None,
483
+ labels: Optional[torch.LongTensor] | None = None,
484
+ use_cache: Optional[bool] | None = None,
485
+ output_attentions: Optional[bool] | None = None,
486
+ output_hidden_states: Optional[bool] | None = None,
487
+ return_dict: Optional[bool] | None = None,
488
+ **kwargs,
489
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
490
+ r"""
491
+ Args:
492
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
493
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
494
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
495
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
496
+ Returns:
497
+ """
498
+
499
+ samples = kwargs.get("samples", None)
500
+ if samples:
501
+ infer_mode = samples.get("infer_mode", "base")
502
+ if samples["data_type"][0] == "multi":
503
+ has_img = True
504
+ else:
505
+ has_img = False
506
+
507
+ # encode text
508
+ text = samples["text_input"]
509
+ # encode image
510
+ if has_img:
511
+ image = samples["image"][0]
512
+ bs = len(samples["text_input"][0])
513
+ image_nums = []
514
+ temp_image = []
515
+ for im in image:
516
+ if type(im) is list:
517
+ image_nums.append(len(im))
518
+ temp_image.extend(im)
519
+ else:
520
+ image_nums.append(1)
521
+ temp_image.append(im)
522
+ image = temp_image
523
+ assert type(image) is list and len(image_nums) == bs
524
+
525
+ to_regress_embeds, attention_mask, targets, im_mask = (
526
+ self.interleav_wrap(image, text, image_nums)
527
+ )
528
+ else:
529
+ to_regress_tokens, targets = self.text2emb(
530
+ text, add_special_tokens=True
531
+ )
532
+ to_regress_embeds = self.model.tok_embeddings(
533
+ to_regress_tokens.input_ids
534
+ )
535
+ attention_mask = to_regress_tokens.attention_mask
536
+ im_mask = torch.zeros(to_regress_embeds.shape[:2]).cuda()
537
+
538
+ inputs_embeds = to_regress_embeds[:, : self.max_length] # type: ignore
539
+ attention_mask = attention_mask[:, : self.max_length] # type: ignore
540
+ targets = targets[:, : self.max_length]
541
+ im_mask = im_mask[:, : self.max_length].bool()
542
+ labels = targets # type: ignore
543
+ else:
544
+ im_mask = kwargs.get("im_mask", None)
545
+ infer_mode = kwargs.get("infer_mode", "base")
546
+ if im_mask is None and inputs_embeds is not None:
547
+ im_mask = torch.zeros(inputs_embeds.shape[:2]).to(inputs_embeds.device)
548
+ im_mask = im_mask.bool()
549
+
550
+ output_attentions = (
551
+ output_attentions
552
+ if output_attentions is not None
553
+ else self.config.output_attentions
554
+ )
555
+ output_hidden_states = (
556
+ output_hidden_states
557
+ if output_hidden_states is not None
558
+ else self.config.output_hidden_states
559
+ )
560
+ return_dict = (
561
+ return_dict if return_dict is not None else self.config.use_return_dict
562
+ )
563
+
564
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
565
+ outputs = self.model(
566
+ input_ids=input_ids,
567
+ attention_mask=attention_mask,
568
+ position_ids=position_ids,
569
+ past_key_values=past_key_values,
570
+ inputs_embeds=inputs_embeds,
571
+ use_cache=use_cache,
572
+ output_attentions=output_attentions,
573
+ output_hidden_states=output_hidden_states,
574
+ return_dict=return_dict,
575
+ im_mask=im_mask,
576
+ infer_mode=infer_mode,
577
+ )
578
+
579
+ hidden_states = outputs[0]
580
+ logits = self.output(hidden_states)
581
+ logits = logits.float()
582
+
583
+ loss = None
584
+ if labels is not None:
585
+ # Shift so that tokens < n predict n
586
+ shift_logits = logits[..., :-1, :].contiguous()
587
+ shift_labels = labels[..., 1:].contiguous()
588
+ # Flatten the tokens
589
+ loss_fct = CrossEntropyLoss()
590
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
591
+ shift_labels = shift_labels.view(-1)
592
+ # Enable model parallelism
593
+ shift_labels = shift_labels.to(shift_logits.device)
594
+ loss = loss_fct(shift_logits, shift_labels)
595
+
596
+ if not return_dict:
597
+ output = (logits,) + outputs[1:]
598
+ return (loss,) + output if loss is not None else output
599
+
600
+ return CausalLMOutputWithPast(
601
+ loss=loss,
602
+ logits=logits,
603
+ past_key_values=outputs.past_key_values,
604
+ hidden_states=outputs.hidden_states,
605
+ attentions=outputs.attentions,
606
+ )
607
+
608
+ def prepare_inputs_for_generation(
609
+ self,
610
+ input_ids,
611
+ past_key_values=None,
612
+ attention_mask=None,
613
+ inputs_embeds=None,
614
+ im_mask=None,
615
+ infer_mode="base",
616
+ **kwargs,
617
+ ):
618
+ if past_key_values is not None:
619
+ past_length = past_key_values[0][0].shape[2]
620
+
621
+ # Some generation methods already pass only the last input ID
622
+ if input_ids.shape[1] > past_length:
623
+ remove_prefix_length = past_length
624
+ else:
625
+ # Default to old behavior: keep only final ID
626
+ remove_prefix_length = input_ids.shape[1] - 1
627
+
628
+ input_ids = input_ids[:, remove_prefix_length:]
629
+
630
+ position_ids = kwargs.get("position_ids", None)
631
+ if attention_mask is not None and position_ids is None:
632
+ # create position_ids on the fly for batch generation
633
+ position_ids = attention_mask.long().cumsum(-1) - 1
634
+ position_ids.masked_fill_(attention_mask == 0, 1)
635
+ if past_key_values:
636
+ position_ids = position_ids[:, -input_ids.shape[1] :]
637
+
638
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
639
+ if inputs_embeds is not None and past_key_values is None:
640
+ model_inputs = {"inputs_embeds": inputs_embeds}
641
+ else:
642
+ model_inputs = {"input_ids": input_ids}
643
+
644
+ im_mask = im_mask
645
+
646
+ model_inputs.update(
647
+ {
648
+ "position_ids": position_ids,
649
+ "past_key_values": past_key_values,
650
+ "use_cache": kwargs.get("use_cache"),
651
+ "attention_mask": attention_mask,
652
+ "im_mask": im_mask,
653
+ "infer_mode": infer_mode,
654
+ }
655
+ )
656
+ return model_inputs
657
+
658
+ @staticmethod
659
+ def _reorder_cache(past_key_values, beam_idx):
660
+ reordered_past = ()
661
+ for layer_past in past_key_values:
662
+ reordered_past += (
663
+ tuple(
664
+ past_state.index_select(0, beam_idx.to(past_state.device))
665
+ for past_state in layer_past
666
+ ),
667
+ )
668
+ return reordered_past
669
+
670
+ def build_inputs(
671
+ self,
672
+ tokenizer,
673
+ query: str,
674
+ history: List[Tuple[str, str]] = [],
675
+ meta_instruction="",
676
+ ):
677
+ prompt = ""
678
+ if meta_instruction:
679
+ prompt += f"""<s>[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
680
+ else:
681
+ prompt += "<s>"
682
+ for record in history:
683
+ prompt += f"""[UNUSED_TOKEN_146]user\n{record[0]}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n{record[1]}[UNUSED_TOKEN_145]\n"""
684
+ prompt += f"""[UNUSED_TOKEN_146]user\n{query}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n"""
685
+ return tokenizer([prompt], return_tensors="pt")
686
+
687
+ @torch.no_grad()
688
+ def chat(
689
+ self,
690
+ tokenizer,
691
+ query: str,
692
+ image: List[Tuple[str, str]] = [],
693
+ hd_num: int = 24,
694
+ history: List[Tuple[str, str]] = [],
695
+ streamer: Optional[BaseStreamer] = None,
696
+ max_new_tokens: int = 1024,
697
+ do_sample: bool = True,
698
+ num_beams: int = 1,
699
+ temperature: float = 1.0,
700
+ top_p: float = 0.8,
701
+ repetition_penalty: float = 1.005,
702
+ infer_mode: str = "base",
703
+ use_meta: bool = False,
704
+ meta_instruction: str = "You are an AI assistant whose name is InternLM-XComposer (浦语·灵笔).\n"
705
+ "- InternLM-XComposer (浦语·灵笔) is a multi-modality conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
706
+ "- InternLM-XComposer (浦语·灵笔) can understand and communicate fluently in the language chosen by the user such as English and 中文.\n"
707
+ "- InternLM-XComposer (浦语·灵笔) is capable of comprehending and articulating responses effectively based on the provided image.",
708
+ **kwargs,
709
+ ):
710
+ if not use_meta:
711
+ meta_instruction = ""
712
+ if image is None:
713
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
714
+ im_mask = torch.zeros(inputs["input_ids"].shape[:2]).cuda().bool()
715
+ else:
716
+ inputs, im_mask, _ = self.interleav_wrap_chat(
717
+ query,
718
+ image,
719
+ history=history,
720
+ meta_instruction=meta_instruction,
721
+ hd_num=hd_num,
722
+ )
723
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
724
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
725
+ eos_token_id = [
726
+ tokenizer.eos_token_id,
727
+ tokenizer.convert_tokens_to_ids(["[UNUSED_TOKEN_145]"])[0],
728
+ ]
729
+ outputs = self.generate(
730
+ **inputs,
731
+ streamer=streamer,
732
+ max_new_tokens=max_new_tokens,
733
+ num_beams=num_beams,
734
+ do_sample=do_sample,
735
+ temperature=temperature,
736
+ top_p=top_p,
737
+ eos_token_id=eos_token_id,
738
+ repetition_penalty=repetition_penalty,
739
+ im_mask=im_mask,
740
+ infer_mode=infer_mode,
741
+ **kwargs,
742
+ )
743
+ if image is None:
744
+ outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
745
+ else:
746
+ outputs = outputs[0].cpu().tolist()
747
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
748
+ response = response.split("[UNUSED_TOKEN_145]")[0]
749
+ history = history + [(query, response)]
750
+ return response, history
751
+
752
+ @torch.no_grad()
753
+ def write_artical(
754
+ self,
755
+ inst: str,
756
+ image: List[Tuple[str, str]] = [],
757
+ hd_num: int = 25,
758
+ history: List[Tuple[str, str]] = [],
759
+ streamer: Optional[BaseStreamer] = None, # type: ignore
760
+ max_new_tokens: int = 1024,
761
+ do_sample: bool = True,
762
+ num_beams: int = 1,
763
+ temperature: float = 1.0,
764
+ top_p: float = 0.8,
765
+ repetition_penalty: float = 1.005,
766
+ max_length: int = 8192,
767
+ seed: int = -1,
768
+ use_meta: bool = False,
769
+ **kwargs,
770
+ ):
771
+ meta_instruction = """You are an AI assistant whose name is InternLM-XComposer (浦语·灵笔).
772
+ - InternLM-XComposer (浦语·灵笔) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.
773
+ - InternLM-XComposer (浦语·灵笔) can understand and communicate fluently in the language chosen by the user such as English and 中文.
774
+ """
775
+ if seed != -1:
776
+ set_seed(seed)
777
+ if len(history):
778
+ print(
779
+ "Only chat function support multi round now, history will be ignored in the artical mode"
780
+ )
781
+ stop_words_ids = [92542]
782
+ stopping_criteria = get_stopping_criteria(stop_words_ids)
783
+
784
+ if not use_meta:
785
+ meta_instruction = ""
786
+ with torch.no_grad():
787
+ inputs, im_mask, len_input_tokens = self.interleav_wrap_chat(
788
+ inst, image, meta_instruction=meta_instruction, max_length=max_length
789
+ )
790
+ with torch.autocast(device_type="cuda", dtype=torch.float16):
791
+ with torch.no_grad():
792
+ generate = self.generate(
793
+ inputs_embeds=inputs["inputs_embeds"],
794
+ do_sample=do_sample,
795
+ num_beams=num_beams,
796
+ temperature=temperature,
797
+ repetition_penalty=repetition_penalty,
798
+ stopping_criteria=stopping_criteria,
799
+ max_new_tokens=max_length - len_input_tokens,
800
+ top_p=0.8,
801
+ top_k=40,
802
+ length_penalty=1.0,
803
+ im_mask=im_mask,
804
+ infer_mode="write",
805
+ )
806
+
807
+ response = generate[0].tolist()
808
+ response = self.tokenizer.decode(response, skip_special_tokens=True) # type: ignore
809
+ # remove eoa
810
+ response = response.replace("[UNUSED_TOKEN_145]", "")
811
+ response = response.replace("[UNUSED_TOKEN_146]", "")
812
+
813
+ return response
814
+
815
+ @torch.no_grad()
816
+ def write_webpage(
817
+ self,
818
+ inst: str,
819
+ image: List[Tuple[str, str]] = [],
820
+ max_new_tokens: int = 4800,
821
+ do_sample: bool = True,
822
+ num_beams: int = 2,
823
+ temperature: float = 1.0,
824
+ repetition_penalty: float = 3.0,
825
+ seed: int = -1,
826
+ use_meta: bool = False,
827
+ task: str = "Instruction-aware Webpage Generation",
828
+ **kwargs,
829
+ ):
830
+ if seed != -1:
831
+ set_random_seed(seed, set_cudnn=True)
832
+ with torch.no_grad():
833
+ inputs, im_mask, len_input_tokens = self.interleav_wrap_chat(inst, image)
834
+
835
+ with torch.autocast(device_type="cuda", dtype=torch.float16):
836
+ with torch.no_grad():
837
+ generate = self.generate(
838
+ inputs_embeds=inputs["inputs_embeds"],
839
+ do_sample=do_sample,
840
+ temperature=temperature,
841
+ num_beams=num_beams,
842
+ repetition_penalty=repetition_penalty,
843
+ max_new_tokens=max_new_tokens,
844
+ im_mask=im_mask,
845
+ infer_mode="web",
846
+ )
847
+ response = generate[0].tolist()
848
+ response = self.tokenizer.decode(response, skip_special_tokens=True) # type: ignore
849
+ # remove eoa
850
+ response = response.replace("[UNUSED_TOKEN_145]", "")
851
+ out = response.replace("[UNUSED_TOKEN_146]", "")
852
+ image_type = "random"
853
+ pattern = r"""https://source\.unsplash\.com/random/(\d+)x(\d+)/\?([^'"]+)"""
854
+ if image_type == "placeholder":
855
+ out = re.sub(pattern, r"https://placehold.co/\1x\2", out)
856
+ elif image_type == "random":
857
+ out = re.sub(pattern, r"https://picsum.photos/\1/\2", out)
858
+
859
+ with open(task.replace(" ", "_") + ".html", "w") as f:
860
+ f.write(out)
861
+ return out
862
+
863
+ @torch.no_grad()
864
+ def resume_2_webpage(
865
+ self,
866
+ inst: str,
867
+ image: List[Tuple[str, str]] = [],
868
+ max_new_tokens: int = 4800,
869
+ do_sample: bool = True,
870
+ num_beams: int = 2,
871
+ temperature: float = 1.0,
872
+ repetition_penalty: float = 3.0,
873
+ seed: int = -1,
874
+ use_meta: bool = False,
875
+ task: str = "Resume-to-Personal Page",
876
+ **kwargs,
877
+ ):
878
+ if seed != -1:
879
+ set_random_seed(seed, set_cudnn=True)
880
+ try:
881
+ with open(inst) as fd:
882
+ resume = fd.read()
883
+ except Exception:
884
+ print("The input should be a resume with markdown format.")
885
+ inst = " Generate a personal page using the content in the resume:" + resume
886
+ with torch.no_grad():
887
+ inputs, im_mask, len_input_tokens = self.interleav_wrap_chat(inst, image)
888
+ with torch.autocast(device_type="cuda", dtype=torch.float16):
889
+ with torch.no_grad():
890
+ generate = self.generate(
891
+ inputs_embeds=inputs["inputs_embeds"],
892
+ do_sample=do_sample,
893
+ temperature=temperature,
894
+ num_beams=num_beams,
895
+ repetition_penalty=repetition_penalty,
896
+ max_new_tokens=max_new_tokens,
897
+ im_mask=im_mask,
898
+ infer_mode="web",
899
+ )
900
+ response = generate[0].tolist()
901
+ response = self.tokenizer.decode(response, skip_special_tokens=True) # type: ignore
902
+ # remove eoa
903
+ response = response.replace("[UNUSED_TOKEN_145]", "")
904
+ html = response.replace("[UNUSED_TOKEN_146]", "")
905
+
906
+ if seed != -1:
907
+ set_random_seed(seed, set_cudnn=True)
908
+ js_inst = " Generate JavaScript events for the html code:" + html
909
+ with torch.no_grad():
910
+ inputs, im_mask, len_input_tokens = self.interleav_wrap_chat(js_inst, image)
911
+ with torch.autocast(device_type="cuda", dtype=torch.float16):
912
+ with torch.no_grad():
913
+ generate = self.generate(
914
+ inputs_embeds=inputs["inputs_embeds"],
915
+ do_sample=do_sample,
916
+ temperature=temperature,
917
+ num_beams=num_beams,
918
+ repetition_penalty=repetition_penalty,
919
+ max_new_tokens=max_new_tokens,
920
+ im_mask=im_mask,
921
+ infer_mode="web",
922
+ )
923
+ response = generate[0].tolist()
924
+ response = self.tokenizer.decode(response, skip_special_tokens=True) # type: ignore
925
+ # remove eoa
926
+ response = response.replace("[UNUSED_TOKEN_145]", "")
927
+ js = response.replace("[UNUSED_TOKEN_146]", "")
928
+
929
+ if re.search(r"</script>", html):
930
+ js = re.findall(r"<script>([\s\S]*?)<\/script>", js)
931
+ html = re.sub(r"(</script>)", f"\n{js}\n" + r"\1", html)
932
+ elif re.search(r"</html>", html):
933
+ html = re.sub(r"(</html>)", f"\n{js}\n" + r"\1", html)
934
+ out = html
935
+
936
+ image_type = "random"
937
+ pattern = r"""https://source\.unsplash\.com/random/(\d+)x(\d+)/\?([^'"]+)"""
938
+ if image_type == "placeholder":
939
+ out = re.sub(pattern, r"https://placehold.co/\1x\2", out)
940
+ elif image_type == "random":
941
+ out = re.sub(pattern, r"https://picsum.photos/\1/\2", out)
942
+
943
+ with open(task.replace(" ", "_") + ".html", "w") as f:
944
+ f.write(out)
945
+ return out
946
+
947
+ @torch.no_grad()
948
+ def screen_2_webpage(
949
+ self,
950
+ inst: str,
951
+ image: List[Tuple[str, str]] = [],
952
+ max_new_tokens: int = 4800,
953
+ do_sample: bool = True,
954
+ num_beams: int = 2,
955
+ temperature: float = 1.0,
956
+ repetition_penalty: float = 3.0,
957
+ seed: int = -1,
958
+ use_meta: bool = False,
959
+ task: str = "Screenshot-to-Webpage",
960
+ **kwargs,
961
+ ):
962
+ if seed != -1:
963
+ set_random_seed(seed, set_cudnn=True)
964
+ if len(image) == 0:
965
+ print("No image is provided, skip")
966
+ return ""
967
+ inst = " Generate the HTML code of this web image with Tailwind CSS."
968
+ with torch.no_grad():
969
+ inputs, im_mask, len_input_tokens = self.interleav_wrap_chat(inst, image)
970
+
971
+ with torch.autocast(device_type="cuda"):
972
+ with torch.no_grad():
973
+ generate = self.generate(
974
+ inputs_embeds=inputs["inputs_embeds"],
975
+ do_sample=do_sample,
976
+ temperature=temperature,
977
+ num_beams=num_beams,
978
+ repetition_penalty=repetition_penalty,
979
+ max_new_tokens=max_new_tokens,
980
+ im_mask=im_mask,
981
+ infer_mode="web",
982
+ )
983
+ response = generate[0].tolist()
984
+ response = self.tokenizer.decode(response, skip_special_tokens=True) # type: ignore
985
+ # remove eoa
986
+ response = response.replace("[UNUSED_TOKEN_145]", "")
987
+ out = response.replace("[UNUSED_TOKEN_146]", "")
988
+ image_type = "random"
989
+ pattern = r"""https://source\.unsplash\.com/random/(\d+)x(\d+)/\?([^'"]+)"""
990
+ if image_type == "placeholder":
991
+ out = re.sub(pattern, r"https://placehold.co/\1x\2", out)
992
+ elif image_type == "random":
993
+ out = re.sub(pattern, r"https://picsum.photos/\1/\2", out)
994
+
995
+ with open(task.replace(" ", "_") + ".html", "w") as f:
996
+ f.write(out)
997
+ return out
pytorch_model-00001-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b50f5b8df413dade11f624f55ea317bb0158baee38f1ee5f8ed37cbe93f1ba7
3
+ size 9968266170
pytorch_model-00002-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70a747192e2319f481dfb426cda6f99e75e26652442b8369a9de9c72bb3682f4
3
+ size 9999760331
pytorch_model-00003-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0880b52a0d27935e83f5b3fef2886d626671adb2e56de9162344c904e368490e
3
+ size 2224146928
pytorch_model.bin.index.json ADDED
The diff for this file is too large to render. See raw diff
 
special_tokens_map.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|action_start|>",
6
+ "<|action_end|>",
7
+ "<|interpreter|>",
8
+ "<|plugin|>"
9
+ ],
10
+ "bos_token": {
11
+ "content": "<s>",
12
+ "lstrip": false,
13
+ "normalized": false,
14
+ "rstrip": false,
15
+ "single_word": false
16
+ },
17
+ "eos_token": {
18
+ "content": "</s>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "</s>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "unk_token": {
32
+ "content": "<unk>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ }
38
+ }
tokenization_internlm2.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Tokenization classes for InternLM."""
19
+ import os
20
+ from shutil import copyfile
21
+ from typing import Any, Dict, List, Optional, Tuple
22
+
23
+ import sentencepiece as spm
24
+ from transformers.tokenization_utils import PreTrainedTokenizer
25
+ from transformers.utils import logging
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
30
+
31
+ PRETRAINED_VOCAB_FILES_MAP = {}
32
+
33
+
34
+ # Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer
35
+ class InternLM2Tokenizer(PreTrainedTokenizer):
36
+ """
37
+ Construct a InternLM2 tokenizer. Based on byte-level Byte-Pair-Encoding.
38
+
39
+ Args:
40
+ vocab_file (`str`):
41
+ Path to the vocabulary file.
42
+ """
43
+
44
+ vocab_files_names = VOCAB_FILES_NAMES
45
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
46
+ model_input_names = ["input_ids", "attention_mask"]
47
+ _auto_class = "AutoTokenizer"
48
+
49
+ def __init__(
50
+ self,
51
+ vocab_file,
52
+ unk_token="<unk>",
53
+ bos_token="<s>",
54
+ eos_token="</s>",
55
+ pad_token="</s>",
56
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
57
+ add_bos_token=True,
58
+ add_eos_token=False,
59
+ decode_with_prefix_space=False,
60
+ clean_up_tokenization_spaces=False,
61
+ **kwargs,
62
+ ):
63
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
64
+ self.vocab_file = vocab_file
65
+ self.add_bos_token = add_bos_token
66
+ self.add_eos_token = add_eos_token
67
+ self.decode_with_prefix_space = decode_with_prefix_space
68
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
69
+ self.sp_model.Load(vocab_file)
70
+ self._no_prefix_space_tokens = None
71
+ super().__init__(
72
+ bos_token=bos_token,
73
+ eos_token=eos_token,
74
+ unk_token=unk_token,
75
+ pad_token=pad_token,
76
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
77
+ **kwargs,
78
+ )
79
+
80
+ @property
81
+ def no_prefix_space_tokens(self):
82
+ if self._no_prefix_space_tokens is None:
83
+ vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
84
+ self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith("▁")}
85
+ return self._no_prefix_space_tokens
86
+
87
+ @property
88
+ def vocab_size(self):
89
+ """Returns vocab size"""
90
+ return self.sp_model.get_piece_size()
91
+
92
+ @property
93
+ def bos_token_id(self) -> Optional[int]:
94
+ return self.sp_model.bos_id()
95
+
96
+ @property
97
+ def eos_token_id(self) -> Optional[int]:
98
+ return self.sp_model.eos_id()
99
+
100
+ def get_vocab(self):
101
+ """Returns vocab as a dict"""
102
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
103
+ vocab.update(self.added_tokens_encoder)
104
+ return vocab
105
+
106
+ def _tokenize(self, text):
107
+ """Returns a tokenized string."""
108
+ return self.sp_model.encode(text, out_type=str)
109
+
110
+ def _convert_token_to_id(self, token):
111
+ """Converts a token (str) in an id using the vocab."""
112
+ return self.sp_model.piece_to_id(token)
113
+
114
+ def _convert_id_to_token(self, index):
115
+ """Converts an index (integer) in a token (str) using the vocab."""
116
+ token = self.sp_model.IdToPiece(index)
117
+ return token
118
+
119
+ def _maybe_add_prefix_space(self, tokens, decoded):
120
+ if tokens and tokens[0] not in self.no_prefix_space_tokens:
121
+ return " " + decoded
122
+ else:
123
+ return decoded
124
+
125
+ def convert_tokens_to_string(self, tokens):
126
+ """Converts a sequence of tokens (string) in a single string."""
127
+ current_sub_tokens = []
128
+ out_string = ""
129
+ prev_is_special = False
130
+ for token in tokens:
131
+ # make sure that special tokens are not decoded using sentencepiece model
132
+ if token in self.all_special_tokens:
133
+ if not prev_is_special:
134
+ out_string += " "
135
+ out_string += self.sp_model.decode(current_sub_tokens) + token
136
+ prev_is_special = True
137
+ current_sub_tokens = []
138
+ else:
139
+ current_sub_tokens.append(token)
140
+ prev_is_special = False
141
+ out_string += self.sp_model.decode(current_sub_tokens)
142
+ out_string = self.clean_up_tokenization(out_string)
143
+ out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
144
+ return out_string[1:]
145
+
146
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
147
+ """
148
+ Save the vocabulary and special tokens file to a directory.
149
+
150
+ Args:
151
+ save_directory (`str`):
152
+ The directory in which to save the vocabulary.
153
+
154
+ Returns:
155
+ `Tuple(str)`: Paths to the files saved.
156
+ """
157
+ if not os.path.isdir(save_directory):
158
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
159
+ return
160
+ out_vocab_file = os.path.join(
161
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
162
+ )
163
+
164
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
165
+ copyfile(self.vocab_file, out_vocab_file)
166
+ elif not os.path.isfile(self.vocab_file):
167
+ with open(out_vocab_file, "wb") as fi:
168
+ content_spiece_model = self.sp_model.serialized_model_proto()
169
+ fi.write(content_spiece_model)
170
+
171
+ return (out_vocab_file,)
172
+
173
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
174
+ if self.add_bos_token:
175
+ bos_token_ids = [self.bos_token_id]
176
+ else:
177
+ bos_token_ids = []
178
+
179
+ output = bos_token_ids + token_ids_0
180
+
181
+ if token_ids_1 is not None:
182
+ output = output + token_ids_1
183
+
184
+ if self.add_eos_token:
185
+ output = output + [self.eos_token_id]
186
+
187
+ return output
188
+
189
+ def get_special_tokens_mask(
190
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
191
+ ) -> List[int]:
192
+ """
193
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
194
+ special tokens using the tokenizer `prepare_for_model` method.
195
+
196
+ Args:
197
+ token_ids_0 (`List[int]`):
198
+ List of IDs.
199
+ token_ids_1 (`List[int]`, *optional*):
200
+ Optional second list of IDs for sequence pairs.
201
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
202
+ Whether or not the token list is already formatted with special tokens for the model.
203
+
204
+ Returns:
205
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
206
+ """
207
+ if already_has_special_tokens:
208
+ return super().get_special_tokens_mask(
209
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
210
+ )
211
+
212
+ if token_ids_1 is None:
213
+ return [1] + ([0] * len(token_ids_0)) + [1]
214
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
215
+
216
+ def create_token_type_ids_from_sequences(
217
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
218
+ ) -> List[int]:
219
+ """
220
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
221
+ use of token type ids, therefore a list of zeros is returned.
222
+
223
+ Args:
224
+ token_ids_0 (`List[int]`):
225
+ List of IDs.
226
+ token_ids_1 (`List[int]`, *optional*):
227
+ Optional second list of IDs for sequence pairs.
228
+
229
+ Returns:
230
+ `List[int]`: List of zeros.
231
+ """
232
+ eos = [self.eos_token_id]
233
+
234
+ if token_ids_1 is None:
235
+ return len(token_ids_0 + eos) * [0]
236
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f868398fc4e05ee1e8aeba95ddf18ddcc45b8bce55d5093bead5bbf80429b48b
3
+ size 1477754
tokenizer_config.json ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<unk>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "92538": {
28
+ "content": "<|plugin|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "92539": {
36
+ "content": "<|interpreter|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "92540": {
44
+ "content": "<|action_end|>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "92541": {
52
+ "content": "<|action_start|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "92542": {
60
+ "content": "<|im_end|>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "92543": {
68
+ "content": "<|im_start|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ }
75
+ },
76
+ "additional_special_tokens": [
77
+ "<|im_start|>",
78
+ "<|im_end|>",
79
+ "<|action_start|>",
80
+ "<|action_end|>",
81
+ "<|interpreter|>",
82
+ "<|plugin|>"
83
+ ],
84
+ "auto_map": {
85
+ "AutoTokenizer": [
86
+ "tokenization_internlm2.InternLM2Tokenizer",
87
+ null
88
+ ]
89
+ },
90
+ "bos_token": "<s>",
91
+ "chat_template": "{{ bos_token }}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
92
+ "clean_up_tokenization_spaces": false,
93
+ "eos_token": "</s>",
94
+ "model_max_length": 1000000000000000019884624838656,
95
+ "pad_token": "</s>",
96
+ "padding_side": "right",
97
+ "tokenizer_class": "InternLM2Tokenizer",
98
+ "unk_token": "<unk>"
99
+ }