root commited on
Commit
de9e682
·
1 Parent(s): e7ab0ec

change to song prep

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +0 -5
  2. README.md +78 -14
  3. app.py +256 -271
  4. codeclm/models/__init__.py +0 -11
  5. codeclm/models/builders.py +0 -150
  6. codeclm/models/codeclm.py +0 -295
  7. codeclm/models/codeclm_gen.py +0 -323
  8. codeclm/models/levo.py +0 -224
  9. codeclm/models/llama/__init__.py +0 -90
  10. codeclm/models/llama/configuration_llama.py +0 -182
  11. codeclm/models/llama/convert_llama_weights_to_hf.py +0 -318
  12. codeclm/models/llama/modeling_llama.py +0 -1246
  13. codeclm/models/llama/tokenization_llama.py +0 -426
  14. codeclm/models/llama/tokenization_llama_fast.py +0 -264
  15. codeclm/models/lm_levo.py +0 -540
  16. codeclm/modules/conditioners.py +0 -718
  17. codeclm/modules/pattern.py +0 -351
  18. codeclm/modules/streaming.py +0 -112
  19. codeclm/tokenizer/Flow1dVAE/audio.py +0 -304
  20. codeclm/tokenizer/Flow1dVAE/configs/models/transformer2D_wocross_inch112_1x4_multi_large.json +0 -26
  21. codeclm/tokenizer/Flow1dVAE/configs/scheduler/stable_diffusion_2.1_largenoise_sample.json +0 -14
  22. codeclm/tokenizer/Flow1dVAE/generate_1rvq.py +0 -228
  23. codeclm/tokenizer/Flow1dVAE/generate_septoken.py +0 -309
  24. codeclm/tokenizer/Flow1dVAE/libs/fsq/fsq.py +0 -236
  25. codeclm/tokenizer/Flow1dVAE/libs/rvq/core_vq.py +0 -366
  26. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize.py +0 -268
  27. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize2.py +0 -290
  28. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_4layer.py +0 -303
  29. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_4layer_freezelayer1.py +0 -301
  30. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_4layer_return_layer.py +0 -305
  31. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_4layer_test.py +0 -307
  32. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_nodown.py +0 -300
  33. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_randomdrop.py +0 -321
  34. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_randomdrop_freezervq.py +0 -323
  35. codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_simple_vq.py +0 -299
  36. codeclm/tokenizer/Flow1dVAE/libs/rvq/mert_with_kmeans.py +0 -187
  37. codeclm/tokenizer/Flow1dVAE/libs/rvq/rvq2.py +0 -149
  38. codeclm/tokenizer/Flow1dVAE/model_septoken.py +0 -675
  39. codeclm/tokenizer/Flow1dVAE/models/attention.py +0 -682
  40. codeclm/tokenizer/Flow1dVAE/models/attention_add_rot_emb.py +0 -734
  41. codeclm/tokenizer/Flow1dVAE/models/test_model.py +0 -92
  42. codeclm/tokenizer/Flow1dVAE/models/transformer_2d.py +0 -487
  43. codeclm/tokenizer/Flow1dVAE/models/transformer_2d_additionalemb.py +0 -468
  44. codeclm/tokenizer/Flow1dVAE/models/transformer_2d_flow.py +0 -545
  45. codeclm/tokenizer/Flow1dVAE/models/transformer_2d_rot_emb.py +0 -487
  46. codeclm/tokenizer/Flow1dVAE/models/unet_2d_condition_additionalemb.py +0 -996
  47. codeclm/tokenizer/Flow1dVAE/models/unet_2d_condition_flow.py +0 -934
  48. codeclm/tokenizer/Flow1dVAE/models_gpt/models/attention.py +0 -668
  49. codeclm/tokenizer/Flow1dVAE/models_gpt/models/attention_add_rot_emb.py +0 -724
  50. codeclm/tokenizer/Flow1dVAE/models_gpt/models/gpt2.py +0 -1954
Dockerfile CHANGED
@@ -7,11 +7,6 @@ RUN apt-get update && \
7
  git lfs install && \
8
  rm -rf /var/lib/apt/lists/*
9
 
10
- COPY ./vllm_hacked/model_executor/models/llama.py /opt/conda/lib/python3.11/site-packages/vllm/model_executor/models/llama.py
11
- COPY ./vllm_hacked/v1/sample/sampler.py /opt/conda/lib/python3.11/site-packages/vllm/v1/sample/sampler.py
12
- COPY ./vllm_hacked/v1/sample/metadata.py /opt/conda/lib/python3.11/site-packages/vllm/v1/sample/metadata.py
13
- COPY ./vllm_hacked/sampling_params.py /opt/conda/lib/python3.11/site-packages/vllm/sampling_params.py
14
-
15
  RUN useradd -m -u 1000 user
16
  USER user
17
  ENV PATH="/home/user/.local/bin:$PATH"
 
7
  git lfs install && \
8
  rm -rf /var/lib/apt/lists/*
9
 
 
 
 
 
 
10
  RUN useradd -m -u 1000 user
11
  USER user
12
  ENV PATH="/home/user/.local/bin:$PATH"
README.md CHANGED
@@ -1,16 +1,80 @@
1
- ---
2
- title: Song Generation
3
- emoji: 🎵
4
- colorFrom: purple
5
- colorTo: gray
6
- sdk: docker
7
- app_port: 7860
8
- models:
9
- - tencent/SongGeneration
10
- ---
11
-
12
-
13
  <p align="center">
14
- <a href="https://levo-demo.github.io/">Demo</a> &nbsp;|&nbsp; <a href="https://arxiv.org/abs/2506.07520">Paper</a> &nbsp;|&nbsp; <a href="https://github.com/tencent-ailab/songgeneration">Code</a>
15
  </p>
16
- This repository is the official weight repository for LeVo: High-Quality Song Generation with Multi-Preference Alignment. In this repository, we provide the SongGeneration model, inference scripts, and the checkpoint that has been trained on the Million Song Dataset.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SongPrep
2
+ <p align="center"><img src="img/logo.jpg" width="40%"></p>
 
 
 
 
 
 
 
 
 
 
3
  <p align="center">
4
+ <a href="https://song-prep.github.io/demo/">Demo</a> &nbsp;|&nbsp; <a href="https://arxiv.org/abs/2509.17404">Paper</a> &nbsp;|&nbsp; <a href="https://huggingface.co/waytan22/SongPrep-7B">Weight</a> &nbsp;|&nbsp; <a href="https://huggingface.co/datasets/waytan22/SSLD-200">Dataset</a>
5
  </p>
6
+ This repository is the official code repository for SongPrep: A Preprocessing Framework and End-to-end Model for Full-song Structure Parsing and Lyrics Transcription. SongPrep is able to analyze the structure and lyrics of entire songs and provide precise timestamps without the need for additional source separation. In this repository, we provide the SongPrep model, inference scripts, and checkpoints trained on the Million Song Dataset that support both Chinese and English.
7
+
8
+
9
+ ## Evaluation
10
+ Results are reported in Diarization Error Rate (DER) for structure parsing and Word Error Rate (WER) for lyrics transcription.
11
+ | Model | #Params | WER | DER |
12
+ |:----------------:|:-------:|:--------:|:--------:|
13
+ | SongPrep | 7B | **23.5%** | **18.2%** |
14
+ | Gemini-2.5 | - | 29.2% | 94.6% |
15
+ | Seed-ASR | 12B+ | 104.1% | - |
16
+ | Qwen3-ASR | - | 33.3% | - |
17
+ | Qwen-Audio | 8.4B | 232.7% | - |
18
+
19
+
20
+ ## Installation
21
+
22
+ ### Start from scratch
23
+
24
+ You can install the necessary dependencies using the `requirements.txt` file with Python>=3.8.12 and CUDA>=11.8:
25
+ ```bash
26
+ pip install -r requirements.txt
27
+ ```
28
+
29
+ ## Usage
30
+ To ensure the model runs correctly, please **download the weight** from the original source at [Hugging Face](https://huggingface.co/waytan22/SongPrep-7B), and save it into **root directory** of the project.
31
+
32
+ Once everything is set up, you can run the inference script using the following command:
33
+
34
+ ### With transformers
35
+ ```bash
36
+ python3 run.py -i your_wav_path
37
+ ```
38
+ The complete output may look like:
39
+ ```bash
40
+ [structure][start:end]lyric ; [structure][start:end]lyric ; [structure][start:end]lyric
41
+ ```
42
+ - The song is divided into segments by ';'.
43
+ - The **structure** is the label from structure analysis for the segment.
44
+ - The **start** and **end** are the segment’s start and end times.
45
+ - The lyric is the recognized lyrics, where sentences separated by '.'.
46
+
47
+
48
+ ### With vllm
49
+ ```bash
50
+ python3 run.py -i your_wav_dir
51
+ ```
52
+
53
+ The complete output may look like:
54
+ ```bash
55
+ =====wav_name=====
56
+ [structure][start:end]lyric ; [structure][start:end]lyric ; [structure][start:end]lyric
57
+
58
+ =====wav_name=====
59
+ [structure][start:end]lyric ; [structure][start:end]lyric ; [structure][start:end]lyric
60
+
61
+ =====wav_name=====
62
+ [structure][start:end]lyric ; [structure][start:end]lyric ; [structure][start:end]lyric
63
+ ```
64
+
65
+ ## Citation
66
+ ```
67
+ @misc{tan2025songpreppreprocessingframeworkendtoend,
68
+ title={SongPrep: A Preprocessing Framework and End-to-end Model for Full-song Structure Parsing and Lyrics Transcription},
69
+ author={Wei Tan and Shun Lei and Huaicheng Zhang and Guangzheng Li and Yixuan Zhang and Hangting Chen and Jianwei Yu and Rongzhi Gu and Dong Yu},
70
+ year={2025},
71
+ eprint={2509.17404},
72
+ archivePrefix={arXiv},
73
+ primaryClass={eess.AS},
74
+ url={https://arxiv.org/abs/2509.17404},
75
+ }
76
+ ```
77
+
78
+ ## License
79
+ The code and weights in this repository is released in the [LICENSE](LICENSE) file.
80
+
app.py CHANGED
@@ -1,294 +1,279 @@
1
- import gradio as gr
2
- import json
3
- from datetime import datetime
4
- import yaml
5
- import time
6
- import re
7
  import os
8
  import os.path as op
9
- import torch
10
- import soundfile as sf
11
- import numpy as np
12
  import tempfile
 
 
 
 
 
13
 
14
  from download import download_model
15
 
16
- # 下载模型
 
 
17
  APP_DIR = op.dirname(op.abspath(__file__))
18
- download_model(APP_DIR, repo_id="waytan22/SongGeneration-v2.0", revision="ffd9215")
19
  print("Successful downloaded model.")
20
 
21
- # 模型初始化
22
- from levo_inference import LeVoInference
23
- Model = None
24
-
25
- EXAMPLE_LYRICS = """
26
- [intro-medium]
27
-
28
- [verse]
29
- 列车呼啸穿过隧道
30
- 窗外风景急速倒退
31
- 像是与过去在告别
32
- 奔向未定的终点线
33
- 心中混杂期待恐惧
34
- 请别问我要去哪里
35
- 也别追问归期何时
36
-
37
- [chorus]
38
- 让我随风去流浪
39
- 我不想停留原地
40
- 原地只有无尽循环
41
- 不再规划人生
42
- 不再遵循地图
43
- 我渴望一场意外之旅
44
- 邂逅未知的自己
45
-
46
- [inst-short]
47
-
48
- [verse]
49
- 行李简单只有背囊
50
- 装着一颗渴望自由的心
51
- 旧照片已撕碎抛洒
52
- 不要任何牵绊
53
- 不要沉重过往
54
-
55
- [chorus]
56
- 让我随风去流浪
57
- 我不想停留原地
58
- 原地只会滋生腐朽
59
- 不再规划人生
60
- 不再遵循地图
61
- 我渴望一场灵魂蜕变
62
- 在路途中找到答案
63
-
64
- [bridge]
65
- 山川湖海皆是导师
66
- 星空之下顿悟了渺小
67
- 狭隘的悲欢被风吹散
68
- 融入天地间的壮阔
69
-
70
- [chorus]
71
- 它教会我何为生命
72
- 何为存在的意义
73
- 渺小如尘却也独特
74
- 勇敢地写下自己的诗
75
- 这是我的远征之路
76
- 生命最绚烂的章节
77
-
78
- [outro-medium]
79
- """.strip()
80
-
81
- with open(op.join(APP_DIR, 'conf/vocab.yaml'), 'r', encoding='utf-8') as file:
82
- STRUCTS = yaml.safe_load(file)
83
-
84
-
85
- def save_as_flac(sample_rate, audio_data):
86
- if isinstance(audio_data, tuple):
87
- sample_rate, audio_data = audio_data
88
-
89
- if audio_data.dtype == np.float64:
90
- audio_data = audio_data.astype(np.float32)
91
-
92
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".flac")
93
- sf.write(temp_file, audio_data, sample_rate, format='FLAC')
94
- return temp_file.name
95
-
96
-
97
- # 模拟歌曲生成函数
98
- def generate_song(lyric, description=None, prompt_audio=None, genre=None, cfg_coef=None, temperature=0.1, top_k=-1, gen_type="mixed", progress=gr.Progress(track_tqdm=True)):
99
- global MODEL
100
- global STRUCTS
101
- params = {'cfg_coef':cfg_coef, 'temperature':temperature, 'top_k':top_k}
102
- params = {k:v for k,v in params.items() if v is not None}
103
- vocal_structs = ['[verse]', '[chorus]', '[bridge]']
104
- sample_rate = MODEL.cfg.sample_rate
105
-
106
- # format lyric
107
- lyric = lyric.replace("[intro]", "[intro-short]").replace("[inst]", "[inst-short]").replace("[outro]", "[outro-short]")
108
- paragraphs = [p.strip() for p in lyric.strip().split('\n\n') if p.strip()]
109
- if len(paragraphs) < 1:
110
- return None, json.dumps("Lyrics can not be left blank")
111
- paragraphs_norm = []
112
- vocal_flag = False
113
- for para in paragraphs:
114
- lines = para.splitlines()
115
- struct_tag = lines[0].strip().lower()
116
- if struct_tag not in STRUCTS:
117
- return None, json.dumps(f"Segments should start with a structure tag in {STRUCTS}")
118
- if struct_tag in vocal_structs:
119
- vocal_flag = True
120
- if len(lines) < 2 or not [line.strip() for line in lines[1:] if line.strip()]:
121
- return None, json.dumps("The following segments require lyrics: [verse], [chorus], [bridge]")
122
- else:
123
- new_para_list = []
124
- for line in lines[1:]:
125
- new_para_list.append(re.sub(r"[^\w\s\[\]\-\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af\u00c0-\u017f]", "", line))
126
- new_para_str = f"{struct_tag} {'.'.join(new_para_list)}"
127
  else:
128
- if len(lines) > 1:
129
- return None, json.dumps("The following segments should not contain lyrics: [intro], [intro-short], [intro-medium], [inst], [inst-short], [inst-medium], [outro], [outro-short], [outro-medium]")
130
- else:
131
- new_para_str = struct_tag
132
- paragraphs_norm.append(new_para_str)
133
- if not vocal_flag:
134
- return None, json.dumps(f"The lyric must contain at least one of the following structures: {vocal_structs}")
135
- lyric_norm = " ; ".join(paragraphs_norm)
136
-
137
- # format prompt
138
- if prompt_audio is not None:
139
- genre = None
140
- description = None
141
- elif description is not None and description != "":
142
- genre = None
143
- if description[-1] != ".":
144
- description = description + "."
145
-
146
- progress(0.0, "Start Generation")
147
- start = time.time()
148
-
149
- audio_data = MODEL(lyric_norm, description, prompt_audio, genre, op.join(APP_DIR, "tools/new_prompt.pt"), gen_type, params).cpu().permute(1, 0).float().numpy()
150
-
151
- end = time.time()
152
-
153
- # 创建输入配置的JSON
154
- input_config = {
155
- "lyric": lyric_norm,
156
- "genre": genre,
157
- "prompt_audio": prompt_audio,
158
- "description": description,
159
- "params": params,
160
- "inference_duration": end - start,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  "timestamp": datetime.now().isoformat(),
 
162
  }
163
-
164
- filepath = save_as_flac(sample_rate, audio_data)
165
- return filepath, json.dumps(input_config, indent=2)
166
 
167
 
168
- # 创建Gradio界面
169
- with gr.Blocks(title="SongGeneration Demo Space") as demo:
170
- gr.Markdown("# 🎵 SongGeneration Demo Space")
171
- gr.Markdown("Push to Levo 2.0 — faster and more controllable. The code is in [GIT](https://github.com/tencent-ailab/SongGeneration)")
172
-
 
 
 
 
 
 
173
  with gr.Row():
174
  with gr.Column():
175
- lyric = gr.Textbox(
176
- label="Lyrics",
177
- lines=5,
178
- max_lines=15,
179
- value=EXAMPLE_LYRICS,
180
- info="Each paragraph represents a segment starting with a structure tag and ending with a blank line, each line is a sentence without punctuation, segments [intro], [inst], [outro] should not contain lyrics, while [verse], [chorus], and [bridge] require lyrics.",
181
- placeholder="""Lyric Format
182
- '''
183
- [structure tag]
184
- lyrics
185
-
186
- [structure tag]
187
- lyrics
188
- '''
189
- 1. One paragraph represents one segments, starting with a structure tag and ending with a blank line
190
- 2. One line represents one sentence, punctuation is not recommended inside the sentence
191
- 3. The following segments should not contain lyrics: [intro-short], [intro-medium], [inst-short], [inst-medium], [outro-short], [outro-medium]
192
- 4. The following segments require lyrics: [verse], [chorus], [bridge]
193
- """
194
  )
 
195
 
196
- with gr.Tabs(elem_id="extra-tabs"):
197
- with gr.Tab("Genre Select"):
198
- genre = gr.Radio(
199
- choices=["Auto", "Pop", "Latin", "Rock", "Electronic", "Metal", "Country", "R&B/Soul", "Ballad", "Jazz", "World", "Hip-Hop", "Funk", "Soundtrack"],
200
- label="Genre Select(Optional)",
201
- value="Auto",
202
- interactive=True,
203
- elem_id="single-select-radio"
204
- )
205
- with gr.Tab("Text Prompt"):
206
- gr.Markdown("For detailed usage, please refer to [here](https://github.com/tencent-ailab/SongGeneration?tab=readme-ov-file#-description-input-format)")
207
- description = gr.Textbox(
208
- label="Song Description (Optional)",
209
- info="Describe the gender, genre, emotion, and instrument. Only English is supported currently.​",
210
- placeholder="female, rock, motivational, electric guitar, bass guitar, drum kit.",
211
- lines=1,
212
- max_lines=2
213
- )
214
- with gr.Tab("Audio Prompt"):
215
- prompt_audio = gr.Audio(
216
- label="Prompt Audio (Optional)",
217
- type="filepath",
218
- elem_id="audio-prompt"
219
- )
220
-
221
- with gr.Accordion("Advanced Config", open=False):
222
- cfg_coef = gr.Slider(
223
- label="CFG Coefficient",
224
- minimum=0.1,
225
- maximum=3.0,
226
- step=0.1,
227
- value=1.8,
228
- interactive=True,
229
- elem_id="cfg-coef",
230
- )
231
- temperature = gr.Slider(
232
- label="Temperature",
233
- minimum=0.1,
234
- maximum=2.0,
235
- step=0.1,
236
- value=0.8,
237
- interactive=True,
238
- elem_id="temperature",
239
- )
240
- # top_k = gr.Slider(
241
- # label="Top-K",
242
- # minimum=1,
243
- # maximum=100,
244
- # step=1,
245
- # value=50,
246
- # interactive=True,
247
- # elem_id="top_k",
248
- # )
249
- with gr.Row():
250
- generate_btn = gr.Button("Generate Song", variant="primary")
251
- # generate_bgm_btn = gr.Button("Generate Pure Music", variant="primary")
252
-
253
  with gr.Column():
254
- output_audio = gr.Audio(label="Generated Song", type="filepath")
255
- output_json = gr.JSON(label="Generated Info")
256
-
257
- # # 示例按钮
258
- # examples = gr.Examples(
259
- # examples=[
260
- # ["male, bright, rock, happy, electric guitar and drums, the bpm is 150."],
261
- # ["female, warm, jazz, romantic, synthesizer and piano, the bpm is 100."]
262
- # ],
263
- # inputs=[description],
264
- # label="Text Prompt examples"
265
- # )
266
-
267
- # examples = gr.Examples(
268
- # examples=[
269
- # "[intro-medium]\n\n[verse]\n在这个疯狂的世界里\n谁不渴望一点改变\n在爱情面前\n我们都显得那么不安全\n你紧紧抱着我\n告诉我再靠近一点\n别让这璀璨的夜晚白白浪费\n我那迷茫的眼睛\n看不见未来的路\n在情感消散之前\n我们对爱的渴望永不熄灭\n你给我留下一句誓言\n想知道我们的爱是否能持续到永远\n[chorus]\n\n约定在那最后的夜晚\n不管命运如何摆布\n我们的心是否依然如初\n我会穿上红衬衫\n带着摇滚的激情\n回到我们初遇的地方\n约定在那最后的夜晚\n就算全世界都变了样\n我依然坚守诺言\n铭记这一天\n你永远是我心中的爱恋\n\n[outro-medium]\n",
270
- # "[intro-short]\n\n[verse]\nThrough emerald canyons where fireflies dwell\nCerulean berries kiss morning's first swell\nCrystalline dew crowns each Vitamin Dawn's confection dissolves slowly on me\nAmbrosia breezes through honeycomb vines\nNature's own candy in Fibonacci lines\n[chorus] Blueberry fruit so sweet\n takes you higher\n can't be beat\n In your lungs\n it starts to swell\n You're under its spell\n [verse] Resin of sunlight in candied retreat\nMarmalade moonbeams melt under bare feet\nNectar spirals bloom chloroplast champagne\nPhotosynthesis sings through my veins\nChlorophyll rhythms pulse warm in my blood\nThe forest's green pharmacy floods every bud[chorus] Blueberry fruit so sweet\n takes you higher\n can't be beat\n In your lungs\n it starts to swell\n You're under its spell\n feel the buzz\n ride the wave\n Limey me\n blueberry\n your mind's enslaved\n In the haze\n lose all time\n floating free\n feeling fine\n Blueberry\n fruit so sweet\n takes you higher\n can't be beat\n In your lungs\n it starts to swell\n cry\n You're under its spell\n\n[outro-short]\n",
271
- # ],
272
- # inputs=[lyric],
273
- # label="Lyrics examples",
274
- # )
275
-
276
- # 生成按钮点击事件
277
- generate_btn.click(
278
- fn=generate_song,
279
- inputs=[lyric, description, prompt_audio, genre, cfg_coef, temperature, gr.State(5000)],
280
- outputs=[output_audio, output_json]
281
  )
282
- # generate_bgm_btn.click(
283
- # fn=generate_song,
284
- # inputs=[lyric, description, prompt_audio, genre, cfg_coef, temperature, gr.State(50), gr.State("bgm")],
285
- # outputs=[output_audio, output_json]
286
- # )
287
-
288
-
289
- # 启动应用
290
  if __name__ == "__main__":
291
  torch.set_num_threads(1)
292
- MODEL = LeVoInference(op.join(APP_DIR, "ckpt"))
293
- demo.launch(server_name="0.0.0.0", server_port=7860)
294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import os.path as op
3
+ import re
4
+ import time
5
+ import json
6
  import tempfile
7
+ from datetime import datetime
8
+
9
+ import gradio as gr
10
+ import torch
11
+ import torchaudio
12
 
13
  from download import download_model
14
 
15
+ # ---------------------------------------------------------------------------
16
+ # Download model weights (cached after first run)
17
+ # ---------------------------------------------------------------------------
18
  APP_DIR = op.dirname(op.abspath(__file__))
19
+ download_model(APP_DIR)
20
  print("Successful downloaded model.")
21
 
22
+ # ---------------------------------------------------------------------------
23
+ # Patch vLLM validators (same as run_vllm.py) BEFORE importing vllm engines
24
+ # ---------------------------------------------------------------------------
25
+ from vllm.v1.engine.processor import Processor
26
+ from vllm.engine.llm_engine import LLMEngine
27
+
28
+ Processor._validate_model_input = lambda *args, **kwargs: None
29
+ LLMEngine._validate_token_prompt = lambda *args, **kwargs: None
30
+
31
+ from vllm import __version__ as vllm_version
32
+ from vllm import LLM, SamplingParams
33
+ from megatron.tokenizer import build_tokenizer
34
+ from mucodec.generate_1rvq import Tango
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Inference wrappers (ported from run_vllm.py)
39
+ # ---------------------------------------------------------------------------
40
+ class _Args:
41
+ pass
42
+
43
+
44
+ class VllmInf:
45
+ def __init__(self, model_path, vocab_file, tokenizer="Qwen2Tokenizer", extra_vocab_size=16384):
46
+ args = _Args()
47
+ args.vocab_file = vocab_file
48
+ args.load = model_path
49
+ args.extra_vocab_size = extra_vocab_size
50
+ args.patch_tokenizer_type = tokenizer
51
+
52
+ self.tokenizer = build_tokenizer(args)
53
+ self.text_offset = len(self.tokenizer.tokenizer.get_vocab())
54
+ self.max_tokens = 8192
55
+ self.llm = LLM(
56
+ model=model_path,
57
+ trust_remote_code=True,
58
+ max_model_len=self.max_tokens,
59
+ dtype="bfloat16",
60
+ )
61
+
62
+ def run(self, audios):
63
+ batch_token_ids = []
64
+ max_tokens = self.max_tokens
65
+ for audio in audios:
66
+ audio = audio + self.text_offset
67
+ sentence_ids = (
68
+ [self.tokenizer.sep_token_id]
69
+ + audio.tolist()
70
+ + [self.tokenizer.tokenizer.sep_token_id]
71
+ )
72
+ max_tokens = min(max_tokens, self.max_tokens - len(sentence_ids))
73
+ batch_token_ids.append(sentence_ids)
74
+
75
+ sampling_params = SamplingParams(
76
+ n=1,
77
+ max_tokens=max_tokens,
78
+ top_p=0.1,
79
+ temperature=0.1,
80
+ )
81
+
82
+ if vllm_version == "0.8.5":
83
+ outputs = self.llm.generate(
84
+ prompt_token_ids=batch_token_ids,
85
+ sampling_params=sampling_params,
86
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  else:
88
+ inputs = [{"prompt_token_ids": token_ids} for token_ids in batch_token_ids]
89
+ outputs = self.llm.generate(
90
+ prompts=inputs,
91
+ sampling_params=sampling_params,
92
+ )
93
+
94
+ lyrics = []
95
+ for output in outputs:
96
+ generate_ids = output.outputs[0].token_ids
97
+ lyrics.append(self.tokenizer.detokenize(generate_ids))
98
+
99
+ return lyrics
100
+
101
+
102
+ # ---------------------------------------------------------------------------
103
+ # Globals (lazy initialized inside __main__)
104
+ # ---------------------------------------------------------------------------
105
+ TANGO = None
106
+ VLLM_INF = None
107
+
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Output formatting
111
+ # ---------------------------------------------------------------------------
112
+ SEGMENT_PATTERN = re.compile(
113
+ r"\[(?P<structure>[^\[\]]+)\]\s*\[(?P<start>[^\[\]:]+):(?P<end>[^\[\]]+)\]\s*(?P<lyric>[^;]*)"
114
+ )
115
+
116
+
117
+ def parse_lyric_output(raw_text):
118
+ """Parse the raw model output into structured segments.
119
+
120
+ Expected format::
121
+
122
+ [structure][start:end]lyric ; [structure][start:end]lyric ; ...
123
+ """
124
+ if raw_text is None:
125
+ return []
126
+
127
+ segments = []
128
+ for chunk in raw_text.split(";"):
129
+ chunk = chunk.strip()
130
+ if not chunk:
131
+ continue
132
+ m = SEGMENT_PATTERN.search(chunk)
133
+ if m:
134
+ segments.append(
135
+ {
136
+ "structure": m.group("structure").strip(),
137
+ "start": m.group("start").strip(),
138
+ "end": m.group("end").strip(),
139
+ "lyric": m.group("lyric").strip(),
140
+ }
141
+ )
142
+ else:
143
+ segments.append(
144
+ {
145
+ "structure": "unknown",
146
+ "start": "",
147
+ "end": "",
148
+ "lyric": chunk,
149
+ }
150
+ )
151
+ return segments
152
+
153
+
154
+ def format_segments_markdown(segments):
155
+ """Render parsed segments as a friendly Markdown view."""
156
+ if not segments:
157
+ return "*(No lyrics detected)*"
158
+
159
+ lines = []
160
+ for seg in segments:
161
+ struct = seg["structure"]
162
+ start = seg["start"]
163
+ end = seg["end"]
164
+ lyric = seg["lyric"]
165
+
166
+ header_bits = [f"**[{struct}]**"]
167
+ if start or end:
168
+ header_bits.append(f"`{start} - {end}`")
169
+ lines.append(" ".join(header_bits))
170
+
171
+ if lyric:
172
+ for sentence in [s.strip() for s in lyric.split(".") if s.strip()]:
173
+ lines.append(f"- {sentence}")
174
+ lines.append("") # blank line between segments
175
+
176
+ return "\n".join(lines).strip()
177
+
178
+
179
+ # ---------------------------------------------------------------------------
180
+ # Main inference entry point
181
+ # ---------------------------------------------------------------------------
182
+ def transcribe_song(audio_path, progress=gr.Progress(track_tqdm=True)):
183
+ global TANGO, VLLM_INF
184
+
185
+ if audio_path is None or not op.isfile(audio_path):
186
+ return "*(Please upload an audio file first.)*", "", json.dumps(
187
+ {"error": "No audio file provided"}, indent=2
188
+ )
189
+
190
+ progress(0.0, "Loading audio")
191
+ src_wave, fs = torchaudio.load(audio_path)
192
+ if fs != 48000:
193
+ src_wave = torchaudio.functional.resample(src_wave, fs, 48000)
194
+
195
+ progress(0.2, "Encoding audio with codec")
196
+ start_time = time.time()
197
+ code = TANGO.sound2code(src_wave)
198
+ audio_codes = code[0][0].cpu().numpy()
199
+
200
+ progress(0.5, "Running SongPrep transcription")
201
+ lyrics = VLLM_INF.run([audio_codes])
202
+ raw_lyric = lyrics[0] if lyrics else ""
203
+
204
+ elapsed = time.time() - start_time
205
+ progress(1.0, "Done")
206
+
207
+ segments = parse_lyric_output(raw_lyric)
208
+ pretty = format_segments_markdown(segments)
209
+
210
+ info = {
211
+ "filename": op.basename(audio_path),
212
+ "num_segments": len(segments),
213
+ "inference_duration": elapsed,
214
  "timestamp": datetime.now().isoformat(),
215
+ "raw_output": raw_lyric,
216
  }
217
+ return pretty, raw_lyric, json.dumps(info, indent=2, ensure_ascii=False)
 
 
218
 
219
 
220
+ # ---------------------------------------------------------------------------
221
+ # Gradio UI
222
+ # ---------------------------------------------------------------------------
223
+ with gr.Blocks(title="SongPrep Demo Space") as demo:
224
+ gr.Markdown("# 🎶 SongPrep Demo Space")
225
+ gr.Markdown(
226
+ "Upload a song and SongPrep will analyze its **structure** and "
227
+ "transcribe the **lyrics** with timestamps. "
228
+ "Project: [SongPrep on GitHub](https://github.com/tencent-ailab/SongPrep)"
229
+ )
230
+
231
  with gr.Row():
232
  with gr.Column():
233
+ audio_input = gr.Audio(
234
+ label="Upload Song Audio",
235
+ type="filepath",
236
+ sources=["upload"],
237
+ elem_id="song-audio",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  )
239
+ transcribe_btn = gr.Button("Transcribe Song", variant="primary")
240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  with gr.Column():
242
+ pretty_output = gr.Markdown(
243
+ label="Parsed Lyrics",
244
+ value="*(Results will appear here.)*",
245
+ )
246
+ raw_output = gr.Textbox(
247
+ label="Raw Output",
248
+ lines=4,
249
+ max_lines=20,
250
+ show_copy_button=True,
251
+ interactive=False,
252
+ placeholder="[structure][start:end]lyric ; [structure][start:end]lyric ; ...",
253
+ )
254
+ info_output = gr.JSON(label="Inference Info")
255
+
256
+ transcribe_btn.click(
257
+ fn=transcribe_song,
258
+ inputs=[audio_input],
259
+ outputs=[pretty_output, raw_output, info_output],
 
 
 
 
 
 
 
 
 
260
  )
261
+
262
+
263
+ # ---------------------------------------------------------------------------
264
+ # Entry point
265
+ # ---------------------------------------------------------------------------
 
 
 
266
  if __name__ == "__main__":
267
  torch.set_num_threads(1)
 
 
268
 
269
+ qwen_path = APP_DIR
270
+ codec_path = op.join(APP_DIR, "mucodec.safetensors")
271
+ vocab_file = op.join(APP_DIR, "conf/vocab_type.yaml")
272
+
273
+ # 1) Codec model (audio -> discrete tokens)
274
+ TANGO = Tango(model_path=codec_path)
275
+
276
+ # 2) vLLM-based SongPrep model (tokens -> structured lyrics)
277
+ VLLM_INF = VllmInf(qwen_path, vocab_file)
278
+
279
+ demo.launch(server_name="0.0.0.0", server_port=7860)
codeclm/models/__init__.py DELETED
@@ -1,11 +0,0 @@
1
- # Copyright (c) Meta Platforms, Inc. and affiliates.
2
- # All rights reserved.
3
- #
4
- # This source code is licensed under the license found in the
5
- # LICENSE file in the root directory of this source tree.
6
- """
7
- Models for EnCodec, AudioGen, MusicGen, as well as the generic LMModel.
8
- """
9
- # flake8: noqa
10
- from . import builders
11
- from .codeclm import CodecLM
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/builders.py DELETED
@@ -1,150 +0,0 @@
1
- """
2
- All the functions to build the relevant models and modules
3
- from the Hydra config.
4
- """
5
-
6
- import typing as tp
7
-
8
- import omegaconf
9
- import torch
10
- from codeclm.utils.utils import dict_from_config
11
- from codeclm.modules.pattern import (
12
- CodebooksPatternProvider,
13
- DelayedPatternProvider,
14
- )
15
- from codeclm.modules.conditioners import (
16
- BaseConditioner,
17
- QwTokenizerConditioner,
18
- QwTextConditioner,
19
- QuantizedEmbeddingConditioner,
20
- ConditionerProvider,
21
- ConditionFuser,
22
- )
23
-
24
-
25
- def get_audio_tokenizer_model(checkpoint_path: str, cfg: omegaconf.DictConfig):
26
- from codeclm.tokenizer.audio_tokenizer import AudioTokenizer
27
- """Instantiate a compression model."""
28
- if checkpoint_path is None:
29
- return None
30
- if checkpoint_path.startswith('//pretrained/'):
31
- name = checkpoint_path.split('/', 3)[-1]
32
- return AudioTokenizer.get_pretrained(name, cfg.vae_config, cfg.vae_model, 'cuda', mode=cfg.mode)
33
- elif checkpoint_path == "":
34
- return None
35
- else:
36
- name = checkpoint_path
37
- return AudioTokenizer.get_pretrained(name, cfg.vae_config, cfg.vae_model, 'cuda', mode=cfg.mode)
38
-
39
-
40
- def get_audio_tokenizer_model_cpu(checkpoint_path: str, cfg: omegaconf.DictConfig):
41
- from codeclm.tokenizer.audio_tokenizer import AudioTokenizer
42
- """Instantiate a compression model."""
43
- if checkpoint_path is None:
44
- return None
45
- if checkpoint_path.startswith('//pretrained/'):
46
- name = checkpoint_path.split('/', 3)[-1]
47
- return AudioTokenizer.get_pretrained(name, cfg.vae_config, cfg.vae_model, 'cpu', mode=cfg.mode, tango_device='cpu')
48
- elif checkpoint_path == "":
49
- return None
50
- else:
51
- name = checkpoint_path
52
- return AudioTokenizer.get_pretrained(name, cfg.vae_config, cfg.vae_model, 'cpu', mode=cfg.mode, tango_device='cpu')
53
-
54
-
55
- def get_lm_model(cfg: omegaconf.DictConfig, version: str = 'v1.5'): #-> LMModel:
56
- """Instantiate a LM."""
57
- lm_kwargs = dict_from_config(getattr(cfg, 'lm'))
58
-
59
- # n_q: number of RVQ
60
- code_depth = lm_kwargs['code_depth']
61
- q_modeling = lm_kwargs.pop('q_modeling', None)
62
-
63
- # conditioner
64
- condition_provider = get_conditioner_provider(lm_kwargs["dim"], cfg, version=version)
65
-
66
- # codebook pattern: delay
67
- codebooks_pattern_cfg = getattr(cfg, 'codebooks_pattern')
68
- if codebooks_pattern_cfg.modeling is None:
69
- assert q_modeling is not None, \
70
- "LM model should either have a codebook pattern defined or transformer_lm.q_modeling"
71
- codebooks_pattern_cfg = omegaconf.OmegaConf.create(
72
- {'modeling': q_modeling, 'delay': {'delays': list(range(code_depth))}}
73
- )
74
- pattern_provider = get_codebooks_pattern_provider(code_depth, codebooks_pattern_cfg)
75
-
76
- # condition dropout
77
- attribute_dropout = dict_from_config(getattr(cfg, 'attribute_dropout'))
78
- cls_free_guidance = dict_from_config(getattr(cfg, 'classifier_free_guidance'))
79
- cfg_prob, cfg_coef = cls_free_guidance['training_dropout'], cls_free_guidance['inference_coef']
80
-
81
- # condition fuser
82
- fuser = get_condition_fuser(cfg)
83
- lm_type = lm_kwargs['lm_type'] # YCY: For consistency, choose different lm.py based on lm_type
84
- if lm_type == 'Llama':
85
- from .lm_levo import LmModel
86
- return LmModel(
87
- pattern_provider=pattern_provider,
88
- condition_provider=condition_provider,
89
- fuser=fuser,
90
- cfg_dropout=cfg_prob,
91
- cfg_coef=cfg_coef,
92
- attribute_dropout=attribute_dropout,
93
- cfg=cfg,
94
- **lm_kwargs
95
- ).to('cpu')
96
- else:
97
- raise KeyError(f"Unexpected LM model {lm_type}")
98
-
99
-
100
- def get_conditioner_provider(output_dim: int, cfg: omegaconf.DictConfig, version: str = 'v1.0') -> ConditionerProvider:
101
- """Instantiate a conditioning model."""
102
- cfg = getattr(cfg, 'conditioners')
103
- dict_cfg = {} if cfg is None else dict_from_config(cfg)
104
- conditioners: tp.Dict[str, BaseConditioner] = {}
105
- condition_provider_args = dict_cfg.pop('args', {})
106
-
107
- for cond, cond_cfg in dict_cfg.items():
108
- model_type = cond_cfg['model']
109
- model_args = cond_cfg[model_type]
110
- if model_type == 'QwTokenizer':
111
- conditioners[str(cond)] = QwTokenizerConditioner(
112
- output_dim=output_dim,
113
- **model_args
114
- )
115
- elif model_type == "QwTextTokenizer":
116
- conditioners[str(cond)] = QwTextConditioner(
117
- output_dim=output_dim,
118
- version=version,
119
- **model_args
120
- )
121
- elif model_type == "qt_embedding":
122
- conditioners[str(cond)] = QuantizedEmbeddingConditioner(
123
- dim=output_dim,
124
- **model_args
125
- )
126
- else:
127
- raise ValueError(f"Unrecognized conditioning model: {model_type}")
128
- conditioner = ConditionerProvider(conditioners, **condition_provider_args)
129
- return conditioner
130
-
131
-
132
- def get_condition_fuser(cfg: omegaconf.DictConfig) -> ConditionFuser:
133
- """Instantiate a condition fuser object."""
134
- fuser_cfg = getattr(cfg, 'fuser')
135
- fuser_methods = ['sum', 'prepend']
136
- fuse2cond = {k: fuser_cfg[k] for k in fuser_methods}
137
- kwargs = {k: v for k, v in fuser_cfg.items() if k not in fuser_methods}
138
- fuser = ConditionFuser(fuse2cond=fuse2cond, **kwargs)
139
- return fuser
140
-
141
-
142
- def get_codebooks_pattern_provider(code_depth: int, cfg: omegaconf.DictConfig) -> CodebooksPatternProvider:
143
- """Instantiate a codebooks pattern provider object."""
144
- pattern_providers = {
145
- 'delay': DelayedPatternProvider,
146
- }
147
- name = cfg.modeling
148
- kwargs = dict_from_config(cfg.get(name)) if hasattr(cfg, name) else {}
149
- klass = pattern_providers[name]
150
- return klass(code_depth, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/codeclm.py DELETED
@@ -1,295 +0,0 @@
1
- """
2
- Main model for using CodecLM. This will combine all the required components
3
- and provide easy access to the generation API.
4
- """
5
-
6
- import typing as tp
7
- import warnings
8
-
9
- import torch
10
-
11
- from codeclm.tokenizer.audio_tokenizer import AudioTokenizer
12
- from .lm_levo import LmModel
13
- from ..modules.conditioners import ConditioningAttributes, AudioCondition
14
- from ..utils.autocast import TorchAutocast
15
- import torch
16
- from torch.nn import functional as F
17
- import torchaudio
18
- # from optim.ema import EMA
19
-
20
-
21
- MelodyList = tp.List[tp.Optional[torch.Tensor]]
22
- MelodyType = tp.Union[torch.Tensor, MelodyList]
23
-
24
- class CodecLM:
25
- """CodecLM main model with convenient generation API.
26
-
27
- Args:
28
- name (str): name of the model.
29
- compression_model (CompressionModel): Compression model
30
- used to map audio to invertible discrete representations.
31
- lm (LMModel): Language model over discrete representations.
32
- max_duration (float, optional): maximum duration the model can produce,
33
- otherwise, inferred from the training params.
34
- """
35
- def __init__(self, name: str, audiotokenizer: AudioTokenizer, lm: LmModel,
36
- max_duration: tp.Optional[float] = None, seperate_tokenizer: AudioTokenizer = None):
37
- self.name = name
38
- self.audiotokenizer = audiotokenizer
39
- if self.audiotokenizer:
40
- self.frame_rate = self.audiotokenizer.frame_rate
41
- else:
42
- self.frame_rate = 25
43
- self.lm = lm
44
- self.seperate_tokenizer = seperate_tokenizer
45
- # import pdb; pdb.set_trace()
46
- if max_duration is None:
47
- if hasattr(lm, 'cfg'):
48
- max_duration = lm.cfg.dataset.segment_duration # type: ignore
49
- else:
50
- raise ValueError("You must provide max_duration when building directly CodecLM")
51
- assert max_duration is not None
52
-
53
- self.max_duration: float = max_duration
54
- self.device = torch.device("cuda")
55
- self.generation_params: dict = {}
56
- # self.set_generation_params(duration=15) # 15 seconds by default
57
- self.set_generation_params(duration=15, extend_stride=self.max_duration // 2)
58
- self._progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None
59
- if self.device.type == 'cpu':
60
- self.autocast = TorchAutocast(enabled=False)
61
- else:
62
- self.autocast = TorchAutocast(enabled=False)
63
-
64
- def set_generation_params(self, use_sampling: bool = True, top_k: int = 250,
65
- top_p: float = 0.0, temperature: float = 1.0,
66
- duration: float = 30.0, cfg_coef: float = 3.0,
67
- extend_stride: float = 18, record_tokens: bool = False,
68
- record_window: int = 50):
69
- """Set the generation parameters for CodecLM.
70
-
71
- Args:
72
- use_sampling (bool, optional): Use sampling if True, else do argmax decoding. Defaults to True.
73
- top_k (int, optional): top_k used for sampling. Defaults to 250.
74
- top_p (float, optional): top_p used for sampling, when set to 0 top_k is used. Defaults to 0.0.
75
- temperature (float, optional): Softmax temperature parameter. Defaults to 1.0.
76
- duration (float, optional): Duration of the generated waveform. Defaults to 30.0.
77
- cfg_coef (float, optional): Coefficient used for classifier free guidance. Defaults to 3.0.
78
- two_step_cfg (bool, optional): If True, performs 2 forward for Classifier Free Guidance,
79
- instead of batching together the two. This has some impact on how things
80
- are padded but seems to have little impact in practice.
81
- extend_stride: when doing extended generation (i.e. more than 30 seconds), by how much
82
- should we extend the audio each time. Larger values will mean less context is
83
- preserved, and shorter value will require extra computations.
84
- """
85
- assert extend_stride <= self.max_duration, "Cannot stride by more than max generation duration."
86
- self.extend_stride = extend_stride
87
- self.duration = duration
88
- self.generation_params = {
89
- 'use_sampling': use_sampling,
90
- 'temp': temperature,
91
- 'top_k': top_k,
92
- 'top_p': top_p,
93
- 'cfg_coef': cfg_coef,
94
- 'record_tokens': record_tokens,
95
- 'record_window': record_window,
96
- }
97
-
98
- def set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None):
99
- """Override the default progress callback."""
100
- self._progress_callback = progress_callback
101
-
102
- # Inference
103
- def generate(self, lyrics: tp.List[str],
104
- descriptions: tp.List[str],
105
- melody_wavs: torch.Tensor = None,
106
- melody_is_wav: bool = True,
107
- vocal_wavs: torch.Tensor = None,
108
- bgm_wavs: torch.Tensor = None,
109
- return_tokens: bool = False,
110
- ) -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:
111
- """Generate samples conditioned on text and melody.
112
-
113
- Args:
114
- descriptions (list of str): A list of strings used as text conditioning.
115
- melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as
116
- melody conditioning. Should have shape [B, C, T] with B matching the description length,
117
- C=1 or 2. It can be [C, T] if there is a single description. It can also be
118
- a list of [C, T] tensors.
119
- melody_sample_rate: (int): Sample rate of the melody waveforms.
120
- progress (bool, optional): Flag to display progress of the generation process. Defaults to False.
121
- """
122
- if melody_wavs is not None:
123
- if melody_wavs.dim() == 2:
124
- melody_wavs = melody_wavs[None]
125
- if melody_wavs.dim() != 3:
126
- raise ValueError("Melody wavs should have a shape [B, C, T].")
127
- melody_wavs = list(melody_wavs)
128
- if vocal_wavs is not None:
129
- if vocal_wavs.dim() == 2:
130
- vocal_wavs = vocal_wavs[None]
131
- if vocal_wavs.dim() != 3:
132
- raise ValueError("Vocal wavs should have a shape [B, C, T].")
133
- vocal_wavs = list(vocal_wavs)
134
- if bgm_wavs is not None:
135
- if bgm_wavs.dim() == 2:
136
- bgm_wavs = bgm_wavs[None]
137
- if bgm_wavs.dim() != 3:
138
- raise ValueError("BGM wavs should have a shape [B, C, T].")
139
- bgm_wavs = list(bgm_wavs)
140
-
141
- texts, audio_qt_embs = self._prepare_tokens_and_attributes(lyrics=lyrics, melody_wavs=melody_wavs, vocal_wavs=vocal_wavs, bgm_wavs=bgm_wavs, melody_is_wav=melody_is_wav)
142
- tokens = self._generate_tokens(texts, descriptions, audio_qt_embs)
143
-
144
- if (tokens == self.lm.eos_token_id).any():
145
- length = torch.nonzero(torch.eq(tokens, self.lm.eos_token_id))[:,-1].min()
146
- tokens = tokens[...,:length]
147
-
148
- if return_tokens:
149
- return tokens
150
- else:
151
- out = self.generate_audio(tokens)
152
- return out
153
-
154
-
155
- @torch.no_grad()
156
- def _prepare_tokens_and_attributes(
157
- self,
158
- lyrics: tp.Sequence[tp.Optional[str]],
159
- melody_wavs: tp.Optional[MelodyList] = None,
160
- vocal_wavs: tp.Optional[MelodyList] = None,
161
- bgm_wavs: tp.Optional[MelodyList] = None,
162
- melody_is_wav = True
163
- ) -> tp.Tuple[tp.List[str], tp.List[torch.Tensor]]:
164
- """Prepare model inputs.
165
-
166
- Args:
167
- descriptions (list of str): A list of strings used as text conditioning.
168
- prompt (torch.Tensor): A batch of waveforms used for continuation.
169
- melody_wavs (torch.Tensor, optional): A batch of waveforms
170
- used as melody conditioning. Defaults to None.
171
- """
172
- assert len(lyrics) == 1
173
- texts = [lyric for lyric in lyrics]
174
- audio_qt_embs = []
175
- target_melody_token_len = self.lm.cfg.prompt_len * self.frame_rate
176
- # import pdb; pdb.set_trace()
177
- if melody_wavs is None:
178
- melody_tokens = torch.full((1,1,target_melody_token_len), 16385, device=self.device).long()
179
- elif melody_wavs is not None:
180
- if 'prompt_audio' not in self.lm.condition_provider.conditioners:
181
- raise RuntimeError("This model doesn't support melody conditioning. "
182
- "Use the `melody` model.")
183
- assert len(melody_wavs) == len(texts), \
184
- f"number of melody wavs must match number of descriptions! " \
185
- f"got melody len={len(melody_wavs)}, and descriptions len={len(texts)}"
186
- if type(melody_wavs) == list:
187
- melody_wavs = torch.stack(melody_wavs, dim=0)
188
- melody_wavs = melody_wavs.to(self.device)
189
- if melody_is_wav:
190
- melody_tokens, scale = self.audiotokenizer.encode(melody_wavs)
191
- else:
192
- melody_tokens = melody_wavs
193
- if melody_tokens.shape[-1] > target_melody_token_len:
194
- melody_tokens = melody_tokens[...,:target_melody_token_len]
195
- elif melody_tokens.shape[-1] < target_melody_token_len:
196
- melody_tokens = torch.cat([melody_tokens, torch.full((1,1,target_melody_token_len - melody_tokens.shape[-1]), 16385, device=self.device).long()], dim=-1)
197
-
198
- if bgm_wavs is None:
199
- assert vocal_wavs is None, "vocal_wavs is not None when bgm_wavs is None"
200
- bgm_tokens = torch.full((1,1,target_melody_token_len), 16385, device=self.device).long()
201
- vocal_tokens = torch.full((1,1,target_melody_token_len), 16385, device=self.device).long()
202
- else:
203
- assert vocal_wavs is not None, "vocal_wavs is None when bgm_wavs is not None"
204
- if type(vocal_wavs) == list:
205
- vocal_wavs = torch.stack(vocal_wavs, dim=0)
206
- if type(bgm_wavs) == list:
207
- bgm_wavs = torch.stack(bgm_wavs, dim=0)
208
- vocal_wavs = vocal_wavs.to(self.device)
209
- bgm_wavs = bgm_wavs.to(self.device)
210
- if melody_is_wav:
211
- vocal_tokens, bgm_tokens = self.seperate_tokenizer.encode(vocal_wavs, bgm_wavs)
212
- else:
213
- vocal_tokens = vocal_wavs
214
- bgm_tokens = bgm_wavs
215
- assert len(vocal_tokens.shape) == len(bgm_tokens.shape) == 3, \
216
- f"vocal and bgm tokens should have a shape [B, C, T]! " \
217
- f"got vocal len={vocal_tokens.shape}, and bgm len={bgm_tokens.shape}"
218
- assert vocal_tokens.shape[-1] == bgm_tokens.shape[-1], \
219
- f"vocal and bgm tokens should have the same length! " \
220
- f"got vocal len={vocal_tokens.shape[-1]}, and bgm len={bgm_tokens.shape[-1]}"
221
- if bgm_tokens.shape[-1] > target_melody_token_len:
222
- bgm_tokens = bgm_tokens[...,:target_melody_token_len]
223
- elif bgm_tokens.shape[-1] < target_melody_token_len:
224
- bgm_tokens = torch.cat([bgm_tokens, torch.full((1,1,target_melody_token_len - bgm_tokens.shape[-1]), 16385, device=self.device).long()], dim=-1)
225
- if vocal_tokens.shape[-1] > target_melody_token_len:
226
- vocal_tokens = vocal_tokens[...,:target_melody_token_len]
227
- elif vocal_tokens.shape[-1] < target_melody_token_len:
228
- vocal_tokens = torch.cat([vocal_tokens, torch.full((1,1,target_melody_token_len - vocal_tokens.shape[-1]), 16385, device=self.device).long()], dim=-1)
229
- melody_tokens = torch.cat([melody_tokens, vocal_tokens, bgm_tokens], dim=1)
230
- assert melody_tokens.shape[-1] == target_melody_token_len
231
- audio_qt_embs = melody_tokens.long()
232
- return texts, audio_qt_embs
233
-
234
-
235
-
236
- def _generate_tokens(self,
237
- texts: tp.Optional[tp.List[str]] = None,
238
- descriptions: tp.Optional[tp.List[str]] = None,
239
- audio_qt_embs: tp.Optional[tp.List[torch.Tensor]] = None) -> torch.Tensor:
240
- """Generate discrete audio tokens given audio prompt and/or conditions.
241
-
242
- Args:
243
- attributes (list of ConditioningAttributes): Conditions used for generation (text/melody).
244
- prompt_tokens (torch.Tensor, optional): Audio prompt used for continuation.
245
- progress (bool, optional): Flag to display progress of the generation process. Defaults to False.
246
- Returns:
247
- torch.Tensor: Generated audio, of shape [B, C, T], T is defined by the generation params.
248
- """
249
- total_gen_len = int(self.duration * self.frame_rate)
250
- current_gen_offset: int = 0
251
-
252
- def _progress_callback(generated_tokens: int, tokens_to_generate: int):
253
- generated_tokens += current_gen_offset
254
- if self._progress_callback is not None:
255
- # Note that total_gen_len might be quite wrong depending on the
256
- # codebook pattern used, but with delay it is almost accurate.
257
- self._progress_callback(generated_tokens, total_gen_len)
258
- else:
259
- print(f'{generated_tokens: 6d} / {total_gen_len: 6d}', end='\r')
260
-
261
- if self.duration <= self.max_duration:
262
- # generate by sampling from LM, simple case.
263
- with self.autocast:
264
- gen_tokens = self.lm.generate(texts=texts,
265
- descriptions=descriptions,
266
- audio_qt_embs=audio_qt_embs,
267
- max_gen_len=total_gen_len,
268
- **self.generation_params)
269
- else:
270
- raise NotImplementedError(f"duration {self.duration} < max duration {self.max_duration}")
271
- return gen_tokens
272
-
273
- @torch.no_grad()
274
- def generate_audio(self, gen_tokens: torch.Tensor, prompt=None, vocal_prompt=None, bgm_prompt=None, chunked=False, chunk_size=128, gen_type='mixed'):
275
- """Generate Audio from tokens"""
276
- assert gen_tokens.dim() == 3
277
- if self.seperate_tokenizer is not None:
278
- gen_tokens_song = gen_tokens[:, [0], :]
279
- gen_tokens_vocal = gen_tokens[:, [1], :]
280
- gen_tokens_bgm = gen_tokens[:, [2], :]
281
- if gen_type == 'bgm':
282
- gen_tokens_vocal = torch.full_like(gen_tokens_vocal, 3142)
283
- if vocal_prompt is not None:
284
- vocal_prompt = torch.zeros_like(vocal_prompt)
285
- elif gen_type == 'vocal':
286
- gen_tokens_bgm = torch.full_like(gen_tokens_bgm, 9670)
287
- if bgm_prompt is not None:
288
- bgm_prompt = torch.zeros_like(bgm_prompt)
289
- else:
290
- assert gen_type == 'mixed', f"gen_type {gen_type} not supported"
291
- gen_audio_seperate = self.seperate_tokenizer.decode([gen_tokens_vocal, gen_tokens_bgm], vocal_prompt, bgm_prompt, chunked=chunked, chunk_size=chunk_size)
292
- return gen_audio_seperate
293
- else:
294
- gen_audio = self.audiotokenizer.decode(gen_tokens, prompt)
295
- return gen_audio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/codeclm_gen.py DELETED
@@ -1,323 +0,0 @@
1
- """
2
- Main model for using CodecLM. This will combine all the required components
3
- and provide easy access to the generation API.
4
- """
5
-
6
- import typing as tp
7
- import warnings
8
-
9
- import torch
10
-
11
- from codeclm.tokenizer.audio_tokenizer import AudioTokenizer
12
- # from .lm_llama import LMModel
13
- from ..utils.autocast import TorchAutocast
14
- import torch
15
- from torch.nn import functional as F
16
- import torchaudio
17
- # from optim.ema import EMA
18
- from codeclm.utils.utils import dict_from_config
19
- from codeclm.modules.pattern import (
20
- CodebooksPatternProvider,
21
- DelayedPatternProvider,
22
- )
23
- from codeclm.modules.conditioners import (
24
- ConditioningAttributes,
25
- AudioCondition,
26
- BaseConditioner,
27
- QuantizedEmbeddingConditioner,
28
- ConditionerProvider,
29
- ConditionFuser,
30
- QwTextConditioner,
31
- QwTokenizerConditioner,
32
- ClassifierFreeGuidanceDropoutInference,
33
- )
34
- import omegaconf
35
-
36
- def get_conditioner_provider(output_dim: int, cfg: omegaconf.DictConfig, version: str = 'v1.0') -> ConditionerProvider:
37
- """Instantiate a conditioning model."""
38
- cfg = getattr(cfg, 'conditioners')
39
- dict_cfg = {} if cfg is None else dict_from_config(cfg)
40
- conditioners: tp.Dict[str, BaseConditioner] = {}
41
- condition_provider_args = dict_cfg.pop('args', {})
42
-
43
- for cond, cond_cfg in dict_cfg.items():
44
- model_type = cond_cfg['model']
45
- model_args = cond_cfg[model_type]
46
- if model_type == 'QwTokenizer':
47
- conditioners[str(cond)] = QwTokenizerConditioner(
48
- output_dim=output_dim,
49
- **model_args
50
- )
51
- elif model_type == "QwTextTokenizer":
52
- conditioners[str(cond)] = QwTextConditioner(
53
- output_dim=output_dim,
54
- version=version,
55
- **model_args
56
- )
57
- elif model_type == "qt_embedding":
58
- conditioners[str(cond)] = QuantizedEmbeddingConditioner(
59
- dim=output_dim,
60
- **model_args
61
- )
62
- else:
63
- raise ValueError(f"Unrecognized conditioning model: {model_type}")
64
- conditioner = ConditionerProvider(conditioners, **condition_provider_args)
65
- return conditioner
66
-
67
- def get_codebooks_pattern_provider(code_depth: int, cfg: omegaconf.DictConfig) -> CodebooksPatternProvider:
68
- """Instantiate a codebooks pattern provider object."""
69
- pattern_providers = {
70
- 'delay': DelayedPatternProvider,
71
- }
72
- name = cfg.modeling
73
- kwargs = dict_from_config(cfg.get(name)) if hasattr(cfg, name) else {}
74
- klass = pattern_providers[name]
75
- return klass(code_depth, **kwargs)
76
-
77
- MelodyList = tp.List[tp.Optional[torch.Tensor]]
78
- MelodyType = tp.Union[torch.Tensor, MelodyList]
79
-
80
- def get_condition_fuser(cfg: omegaconf.DictConfig) -> ConditionFuser:
81
- """Instantiate a condition fuser object."""
82
- fuser_cfg = getattr(cfg, 'fuser')
83
- fuser_methods = ['sum', 'prepend']
84
- fuse2cond = {k: fuser_cfg[k] for k in fuser_methods}
85
- kwargs = {k: v for k, v in fuser_cfg.items() if k not in fuser_methods}
86
- fuser = ConditionFuser(fuse2cond=fuse2cond, **kwargs)
87
- return fuser
88
-
89
- class CodecLM_gen:
90
- """CodecLM main model with convenient generation API.
91
-
92
- Args:
93
- name (str): name of the model.
94
- compression_model (CompressionModel): Compression model
95
- used to map audio to invertible discrete representations.
96
- lm (LMModel): Language model over discrete representations.
97
- max_duration (float, optional): maximum duration the model can produce,
98
- otherwise, inferred from the training params.
99
- """
100
- def __init__(self, cfg, name: str, audiotokenizer: AudioTokenizer,
101
- max_duration: tp.Optional[float] = None):
102
- self.cfg = cfg
103
- self.name = name
104
- self.audiotokenizer = audiotokenizer
105
- self.seperate_tokenizer = None
106
- if max_duration is None:
107
- max_duration = self.cfg.max_dur
108
- assert max_duration is not None
109
-
110
- self.max_duration: float = max_duration
111
- # self.device = next(iter(lm.parameters())).device
112
- # self.device = next(iter(audiotokenizer.parameters())).device
113
- self.generation_params: dict = {}
114
- # self.set_generation_params(duration=15) # 15 seconds by default
115
- self.set_generation_params(duration=15, extend_stride=self.max_duration // 2)
116
- self._progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None
117
- self.autocast = TorchAutocast(enabled=False)
118
- self.condition_provider = get_conditioner_provider(cfg.lm.dim, self.cfg)
119
- codebooks_pattern_cfg = getattr(cfg, 'codebooks_pattern')
120
- self.pattern_provider = get_codebooks_pattern_provider(cfg.lm.code_depth, codebooks_pattern_cfg)
121
- self.fuser = get_condition_fuser(cfg)
122
- self.eos_token_id = cfg.lm.code_size
123
-
124
-
125
-
126
- @property
127
- def frame_rate(self) -> float:
128
- """Roughly the number of AR steps per seconds."""
129
- return self.audiotokenizer.frame_rate
130
-
131
- @property
132
- def sample_rate(self) -> int:
133
- """Sample rate of the generated audio."""
134
- return self.audiotokenizer.sample_rate
135
-
136
- @property
137
- def audio_channels(self) -> int:
138
- """Audio channels of the generated audio."""
139
- return self.audiotokenizer.channels
140
-
141
- def set_generation_params(self, use_sampling: bool = True, top_k: int = 250,
142
- top_p: float = 0.0, temperature: float = 1.0,
143
- duration: float = 30.0, cfg_coef: float = 3.0,
144
- extend_stride: float = 18, record_tokens: bool = False,
145
- record_window: int = 50):
146
- """Set the generation parameters for CodecLM.
147
-
148
- Args:
149
- use_sampling (bool, optional): Use sampling if True, else do argmax decoding. Defaults to True.
150
- top_k (int, optional): top_k used for sampling. Defaults to 250.
151
- top_p (float, optional): top_p used for sampling, when set to 0 top_k is used. Defaults to 0.0.
152
- temperature (float, optional): Softmax temperature parameter. Defaults to 1.0.
153
- duration (float, optional): Duration of the generated waveform. Defaults to 30.0.
154
- cfg_coef (float, optional): Coefficient used for classifier free guidance. Defaults to 3.0.
155
- two_step_cfg (bool, optional): If True, performs 2 forward for Classifier Free Guidance,
156
- instead of batching together the two. This has some impact on how things
157
- are padded but seems to have little impact in practice.
158
- extend_stride: when doing extended generation (i.e. more than 30 seconds), by how much
159
- should we extend the audio each time. Larger values will mean less context is
160
- preserved, and shorter value will require extra computations.
161
- """
162
- assert extend_stride <= self.max_duration, "Cannot stride by more than max generation duration."
163
- self.extend_stride = extend_stride
164
- self.duration = duration
165
- self.generation_params = {
166
- 'use_sampling': use_sampling,
167
- 'temp': temperature,
168
- 'top_k': top_k,
169
- 'top_p': top_p,
170
- 'cfg_coef': cfg_coef,
171
- 'record_tokens': record_tokens,
172
- 'record_window': record_window,
173
- }
174
-
175
- def set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None):
176
- """Override the default progress callback."""
177
- self._progress_callback = progress_callback
178
-
179
- # Inference
180
- def generate_condition(self, descriptions: tp.List[str],
181
- melody_wavs: torch.Tensor = None,
182
- return_tokens: bool = False,
183
- melody_is_wav: bool = True,
184
- type_info: tp.List[str] = None,
185
- embeded_eosp1: torch.Tensor = None,
186
- ) -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:
187
- if melody_wavs is not None:
188
- if melody_wavs.dim() == 2:
189
- melody_wavs = melody_wavs[None]
190
- if melody_wavs.dim() != 3:
191
- raise ValueError("Melody wavs should have a shape [B, C, T].")
192
- melody_wavs = list(melody_wavs)
193
-
194
- # if melody_is_wav:
195
- # melody_wavs = [wav.mean(dim=-2) for wav in melody_wavs]
196
-
197
- texts, audio_qt_embs = self._prepare_tokens_and_attributes(descriptions=descriptions,
198
- melody_wavs=melody_wavs,
199
- melody_is_wav=melody_is_wav)
200
- fused_input = self.get_condition_tensors(texts, audio_qt_embs, type_info, embeded_eosp1)
201
-
202
- return fused_input, audio_qt_embs
203
-
204
-
205
- @torch.no_grad()
206
- def _prepare_tokens_and_attributes(
207
- self,
208
- descriptions: tp.Sequence[tp.Optional[str]],
209
- melody_wavs: tp.Optional[MelodyList] = None,
210
- melody_is_wav = True
211
- ) -> tp.Tuple[tp.List[str], tp.List[torch.Tensor]]:
212
- """Prepare model inputs.
213
-
214
- Args:
215
- descriptions (list of str): A list of strings used as text conditioning.
216
- prompt (torch.Tensor): A batch of waveforms used for continuation.
217
- melody_wavs (torch.Tensor, optional): A batch of waveforms
218
- used as melody conditioning. Defaults to None.
219
- """
220
- texts = [description for description in descriptions]
221
- audio_qt_embs = []
222
-
223
- if melody_wavs is None:
224
- audio_qt_embs = None
225
- elif melody_wavs is not None:
226
- if 'prompt_audio' not in self.condition_provider.conditioners:
227
- raise RuntimeError("This model doesn't support melody conditioning. "
228
- "Use the `melody` model.")
229
- assert len(melody_wavs) == len(texts), \
230
- f"number of melody wavs must match number of descriptions! " \
231
- f"got melody len={len(melody_wavs)}, and descriptions len={len(texts)}"
232
- if type(melody_wavs) == list:
233
- melody_wavs = torch.stack(melody_wavs, dim=0)
234
- # melody_wavs = melody_wavs.to(self.device)
235
- if melody_is_wav:
236
- melody_tokens, scale = self.audiotokenizer.encode(melody_wavs)
237
- else:
238
- melody_tokens = melody_wavs
239
- target_melody_token_len = self.cfg.prompt_len * self.audiotokenizer.frame_rate
240
- if melody_tokens.shape[-1] > target_melody_token_len:
241
- melody_tokens = melody_tokens[...,:target_melody_token_len]
242
- for melody in melody_tokens:
243
- audio_qt_embs.append(melody.long())
244
- return texts, audio_qt_embs
245
-
246
- @torch.no_grad()
247
- def prepare_condition_tensors(self,
248
- batch_size = 1,
249
- text: tp.Optional[tp.List[str]] = None,
250
- audio_qt_emb: tp.Optional[tp.List[torch.Tensor]] = None,
251
- type_info: tp.Optional[tp.List[str]] = None,
252
- prepare_null_condition = False,
253
- ):
254
- conditions = []
255
- for i in range(batch_size):
256
- attr = ConditioningAttributes()
257
- if 'description' in self.condition_provider.conditioners:
258
- attr["text"]["description"] = ""
259
- if text is not None:
260
- attr["text"]["description"] = text[i]
261
- if 'prompt_audio' in self.condition_provider.conditioners:
262
- if audio_qt_emb is None: # tokenize stage will padding to max length
263
- attr["audio"]['prompt_audio'] = AudioCondition(
264
- wav=torch.zeros((1, self.cfg.audio_tokenizer_code_depth, 0)).long().cuda() + 16385,
265
- length=torch.Tensor([0]).long(),
266
- sample_rate=[self.cfg.sample_rate],)
267
- else:
268
- aT = audio_qt_emb[i].shape[-1]
269
- pattern = self.pattern_provider.get_pattern(aT)
270
- audio_qt_seq, _, _ = pattern.build_pattern_sequence(audio_qt_emb[i][None],
271
- self.eos_token_id, keep_only_valid_steps=False)
272
- attr["audio"]['prompt_audio'] = AudioCondition(
273
- wav=audio_qt_seq.long().cuda(),
274
- length=torch.Tensor([audio_qt_seq.shape[-1]]).long(),
275
- sample_rate=[self.cfg.sample_rate],)
276
- if 'type_info' in self.condition_provider.conditioners:
277
- attr["text"]["type_info"] = ""
278
- if type_info is not None:
279
- attr["text"]["type_info"] = type_info[i]
280
- conditions.append(attr)
281
- if prepare_null_condition:
282
- cfg_inference = ClassifierFreeGuidanceDropoutInference()
283
- null_conditions = cfg_inference(conditions, condition_types=["audio", "text"],
284
- customized=None)
285
- conditions = conditions + null_conditions
286
- print("conditions", conditions)
287
- tokenized_conditions = self.condition_provider.tokenize(conditions)
288
- # import pdb; pdb.set_trace()
289
- condition_tensors = self.condition_provider(tokenized_conditions)
290
- return condition_tensors
291
-
292
- def get_condition_tensors(self, texts, audio_qt_embs, type_info, embeded_eosp1):
293
- condition_tensors = self.prepare_condition_tensors(batch_size=1, text=texts, audio_qt_emb=audio_qt_embs, type_info=type_info, prepare_null_condition=self.cfg.vllm.cfg)
294
- if self.cfg.vllm.cfg:
295
- input_ = torch.cat((embeded_eosp1, embeded_eosp1), dim=0)
296
- else:
297
- input_ = embeded_eosp1
298
- fused_input = self.fuser(input_, condition_tensors)
299
- return fused_input
300
-
301
- @torch.no_grad()
302
- def generate_audio(self, gen_tokens: torch.Tensor, prompt=None, vocal_prompt=None, bgm_prompt=None, chunked=False, chunk_size=128, gen_type='mixed'):
303
- """Generate Audio from tokens"""
304
- assert gen_tokens.dim() == 3
305
- if self.seperate_tokenizer is not None:
306
- gen_tokens_song = gen_tokens[:, [0], :]
307
- gen_tokens_vocal = gen_tokens[:, [1], :]
308
- gen_tokens_bgm = gen_tokens[:, [2], :]
309
- if gen_type == 'bgm':
310
- gen_tokens_vocal = torch.full_like(gen_tokens_vocal, 3142)
311
- if vocal_prompt is not None:
312
- vocal_prompt = torch.zeros_like(vocal_prompt)
313
- elif gen_type == 'vocal':
314
- gen_tokens_bgm = torch.full_like(gen_tokens_bgm, 9670)
315
- if bgm_prompt is not None:
316
- bgm_prompt = torch.zeros_like(bgm_prompt)
317
- else:
318
- assert gen_type == 'mixed', f"gen_type {gen_type} not supported"
319
- gen_audio_seperate = self.seperate_tokenizer.decode([gen_tokens_vocal, gen_tokens_bgm], vocal_prompt, bgm_prompt, chunked=chunked, chunk_size=chunk_size)
320
- return gen_audio_seperate
321
- else:
322
- gen_audio = self.audiotokenizer.decode(gen_tokens, prompt, chunked=chunked, chunk_size=chunk_size)
323
- return gen_audio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/levo.py DELETED
@@ -1,224 +0,0 @@
1
-
2
- from .llama.modeling_llama import LlamaConfig, CausalLMOutputWithPast, BaseModelOutputWithPast, LlamaDecoderLayer, LlamaRMSNorm
3
- from .llama.modeling_llama import LlamaForCausalLM as LlamaForCausalLM_base
4
- from .llama.modeling_llama import LlamaModel as LlamaModel_base
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from typing import Union, Optional, Tuple, List
9
- from packaging import version
10
- import transformers
11
- """
12
- Wrap the original Llama model for potential customized changes.
13
- """
14
-
15
- """main class"""
16
- class CausalLM(LlamaForCausalLM_base):
17
- def __init__(self, config):
18
- super().__init__(config)
19
- self.model = LmModel(config)
20
- self.vocab_size = config.vocab_size
21
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
22
-
23
- def forward(
24
- self,
25
- input_ids: torch.LongTensor = None,
26
- attention_mask: Optional[torch.Tensor] = None,
27
- position_ids: Optional[torch.LongTensor] = None,
28
- past_key_values: Optional[List[torch.FloatTensor]] = None,
29
- inputs_embeds: Optional[torch.FloatTensor] = None,
30
- labels: Optional[torch.LongTensor] = None,
31
- use_cache: Optional[bool] = None,
32
- output_attentions: Optional[bool] = None,
33
- output_hidden_states: Optional[bool] = None,
34
- return_dict: Optional[bool] = None,
35
- ) -> Union[Tuple, CausalLMOutputWithPast]:
36
-
37
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
38
- output_hidden_states = (
39
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
40
- )
41
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
42
-
43
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
44
- outputs = self.model(
45
- input_ids=input_ids,
46
- attention_mask=attention_mask,
47
- position_ids=position_ids,
48
- past_key_values=past_key_values,
49
- inputs_embeds=inputs_embeds,
50
- use_cache=use_cache,
51
- output_attentions=output_attentions,
52
- output_hidden_states=output_hidden_states,
53
- return_dict=return_dict,
54
- )
55
-
56
- hidden_states = outputs[0]
57
- if self.config.pretraining_tp > 1:
58
- lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
59
- logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
60
- logits = torch.cat(logits, dim=-1)
61
- else:
62
- logits = self.lm_head(hidden_states)
63
- logits = logits.float()
64
-
65
- loss = None
66
- if labels is not None:
67
- # Shift so that tokens < n predict n
68
- shift_logits = logits[..., :-1, :].contiguous()
69
- shift_labels = labels[..., 1:].contiguous()
70
- # Flatten the tokens
71
- loss_fct = nn.CrossEntropyLoss()
72
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
73
- shift_labels = shift_labels.view(-1)
74
- # Enable model parallelism
75
- shift_labels = shift_labels.to(shift_logits.device)
76
- loss = loss_fct(shift_logits, shift_labels)
77
-
78
- if not return_dict:
79
- output = (logits,) + outputs[1:]
80
- return (loss,) + output if loss is not None else output
81
-
82
- return CausalLMOutputWithPast(
83
- loss=loss,
84
- logits=logits,
85
- past_key_values=outputs.past_key_values,
86
- hidden_states=hidden_states,
87
- attentions=outputs.attentions,
88
- )
89
-
90
-
91
- """Submodel class"""
92
- class LmModel(LlamaModel_base):
93
- def __init__(self, config: LlamaConfig):
94
- super().__init__(config)
95
- self.padding_idx = config.pad_token_id
96
- self.vocab_size = config.vocab_size
97
- layer_cls = LlamaDecoderLayer # cross attention decoder layer can be overwritten here
98
-
99
- #assert version.parse(transformers.__version__) < version.parse("4.40")
100
-
101
- self.layers = nn.ModuleList([layer_cls(config) for _ in range(config.num_hidden_layers)])
102
- self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
103
-
104
- self.gradient_checkpointing = False
105
- # Initialize weights and apply final processing
106
- self.post_init()
107
- self.gradient_checkpointing_disable()
108
-
109
- def forward(
110
- self,
111
- input_ids: torch.LongTensor = None,
112
- attention_mask: Optional[torch.Tensor] = None,
113
- position_ids: Optional[torch.LongTensor] = None,
114
- past_key_values: Optional[List[torch.FloatTensor]] = None,
115
- inputs_embeds: Optional[torch.FloatTensor] = None,
116
- use_cache: Optional[bool] = None,
117
- output_attentions: Optional[bool] = None,
118
- output_hidden_states: Optional[bool] = None,
119
- return_dict: Optional[bool] = None,
120
- ) -> Union[Tuple, BaseModelOutputWithPast]:
121
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
122
- output_hidden_states = (
123
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
124
- )
125
- use_cache = use_cache if use_cache is not None else self.config.use_cache
126
-
127
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
128
-
129
- # retrieve input_ids and inputs_embeds
130
- if input_ids is not None and inputs_embeds is not None:
131
- raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
132
- elif input_ids is not None:
133
- batch_size, seq_length = input_ids.shape
134
- elif inputs_embeds is not None:
135
- batch_size, seq_length, _ = inputs_embeds.shape
136
- else:
137
- raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
138
-
139
- seq_length_with_past = seq_length
140
- past_key_values_length = 0
141
-
142
- if past_key_values is not None:
143
- past_key_values_length = past_key_values[0][0].shape[2]
144
- seq_length_with_past = seq_length_with_past + past_key_values_length
145
-
146
- if position_ids is None:
147
- device = input_ids.device if input_ids is not None else inputs_embeds.device
148
- position_ids = torch.arange(
149
- past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
150
- )
151
- position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
152
- else:
153
- position_ids = position_ids.view(-1, seq_length).long()
154
-
155
- # embed positions
156
- if attention_mask is None:
157
- attention_mask = torch.ones(
158
- (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
159
- )
160
- attention_mask = self._prepare_decoder_attention_mask(
161
- attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
162
- )
163
-
164
- hidden_states = inputs_embeds
165
-
166
- if self.gradient_checkpointing and self.training:
167
- if use_cache:
168
- use_cache = False
169
-
170
- # decoder layers
171
- all_hidden_states = () if output_hidden_states else None
172
- all_self_attns = () if output_attentions else None
173
- next_decoder_cache = () if use_cache else None
174
-
175
- for idx, decoder_layer in enumerate(self.layers):
176
- if output_hidden_states:
177
- all_hidden_states += (hidden_states,)
178
-
179
- past_key_value = past_key_values[idx] if past_key_values is not None else None
180
-
181
- layer_args = (hidden_states, attention_mask, position_ids,)
182
-
183
- if self.gradient_checkpointing and self.training:
184
-
185
- def create_custom_forward(module):
186
- def custom_forward(*inputs):
187
- # None for past_key_value
188
- return module(*inputs, past_key_value, output_attentions)
189
-
190
- return custom_forward
191
- layer_outputs = torch.utils.checkpoint.checkpoint(
192
- create_custom_forward(decoder_layer), *layer_args
193
- )
194
- else:
195
-
196
- layer_outputs = decoder_layer(*layer_args,
197
- past_key_value=past_key_value,
198
- output_attentions=output_attentions,
199
- use_cache=use_cache)
200
-
201
- hidden_states = layer_outputs[0]
202
-
203
- if use_cache:
204
- next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
205
-
206
- if output_attentions:
207
- all_self_attns += (layer_outputs[1],)
208
-
209
- hidden_states = self.norm(hidden_states)
210
-
211
- # add hidden states from the last decoder layer
212
- if output_hidden_states:
213
- all_hidden_states += (hidden_states,)
214
-
215
- next_cache = next_decoder_cache if use_cache else None
216
- if not return_dict:
217
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
218
- return BaseModelOutputWithPast(
219
- last_hidden_state=hidden_states,
220
- past_key_values=next_cache,
221
- hidden_states=all_hidden_states,
222
- attentions=all_self_attns,
223
- )
224
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/llama/__init__.py DELETED
@@ -1,90 +0,0 @@
1
- # Copyright 2022 EleutherAI and The HuggingFace Inc. team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import TYPE_CHECKING
15
-
16
- from transformers.utils import (
17
- OptionalDependencyNotAvailable,
18
- _LazyModule,
19
- is_sentencepiece_available,
20
- is_tokenizers_available,
21
- is_torch_available,
22
- )
23
-
24
-
25
- _import_structure = {
26
- "configuration_llama": ["LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "LlamaConfig"],
27
- }
28
-
29
- try:
30
- if not is_sentencepiece_available():
31
- raise OptionalDependencyNotAvailable()
32
- except OptionalDependencyNotAvailable:
33
- pass
34
- else:
35
- _import_structure["tokenization_llama"] = ["LlamaTokenizer"]
36
-
37
- try:
38
- if not is_tokenizers_available():
39
- raise OptionalDependencyNotAvailable()
40
- except OptionalDependencyNotAvailable:
41
- pass
42
- else:
43
- _import_structure["tokenization_llama_fast"] = ["LlamaTokenizerFast"]
44
-
45
- try:
46
- if not is_torch_available():
47
- raise OptionalDependencyNotAvailable()
48
- except OptionalDependencyNotAvailable:
49
- pass
50
- else:
51
- _import_structure["modeling_llama"] = [
52
- "LlamaForCausalLM",
53
- "LlamaModel",
54
- "LlamaPreTrainedModel",
55
- "LlamaForSequenceClassification",
56
- ]
57
-
58
-
59
- if TYPE_CHECKING:
60
- from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig
61
-
62
- try:
63
- if not is_sentencepiece_available():
64
- raise OptionalDependencyNotAvailable()
65
- except OptionalDependencyNotAvailable:
66
- pass
67
- else:
68
- from .tokenization_llama import LlamaTokenizer
69
-
70
- try:
71
- if not is_tokenizers_available():
72
- raise OptionalDependencyNotAvailable()
73
- except OptionalDependencyNotAvailable:
74
- pass
75
- else:
76
- from .tokenization_llama_fast import LlamaTokenizerFast
77
-
78
- try:
79
- if not is_torch_available():
80
- raise OptionalDependencyNotAvailable()
81
- except OptionalDependencyNotAvailable:
82
- pass
83
- else:
84
- from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel
85
-
86
-
87
- else:
88
- import sys
89
-
90
- sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/llama/configuration_llama.py DELETED
@@ -1,182 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
- #
4
- # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
- # and OPT implementations in this library. It has been modified from its
6
- # original forms to accommodate minor architectural differences compared
7
- # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
- #
9
- # Licensed under the Apache License, Version 2.0 (the "License");
10
- # you may not use this file except in compliance with the License.
11
- # You may obtain a copy of the License at
12
- #
13
- # http://www.apache.org/licenses/LICENSE-2.0
14
- #
15
- # Unless required by applicable law or agreed to in writing, software
16
- # distributed under the License is distributed on an "AS IS" BASIS,
17
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
- # See the License for the specific language governing permissions and
19
- # limitations under the License.
20
- """ LLaMA model configuration"""
21
-
22
- from transformers.configuration_utils import PretrainedConfig
23
- from transformers.utils import logging
24
-
25
-
26
- logger = logging.get_logger(__name__)
27
-
28
- LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
-
30
-
31
- class LlamaConfig(PretrainedConfig):
32
- r"""
33
- This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
34
- model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
- defaults will yield a similar configuration to that of the LLaMA-7B.
36
-
37
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
- documentation from [`PretrainedConfig`] for more information.
39
-
40
-
41
- Args:
42
- vocab_size (`int`, *optional*, defaults to 32000):
43
- Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44
- `inputs_ids` passed when calling [`LlamaModel`]
45
- hidden_size (`int`, *optional*, defaults to 4096):
46
- Dimension of the hidden representations.
47
- intermediate_size (`int`, *optional*, defaults to 11008):
48
- Dimension of the MLP representations.
49
- num_hidden_layers (`int`, *optional*, defaults to 32):
50
- Number of hidden layers in the Transformer encoder.
51
- num_attention_heads (`int`, *optional*, defaults to 32):
52
- Number of attention heads for each attention layer in the Transformer encoder.
53
- num_key_value_heads (`int`, *optional*):
54
- This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
- `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
- `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
- converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
- by meanpooling all the original heads within that group. For more details checkout [this
59
- paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
- `num_attention_heads`.
61
- pretraining_tp (`int`, *optional*, defaults to `1`):
62
- Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
63
- document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
64
- necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
65
- issue](https://github.com/pytorch/pytorch/issues/76232).
66
- hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
- The non-linear activation function (function or string) in the decoder.
68
- max_position_embeddings (`int`, *optional*, defaults to 2048):
69
- The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
70
- Llama 2 up to 4096, CodeLlama up to 16384.
71
- initializer_range (`float`, *optional*, defaults to 0.02):
72
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
- rms_norm_eps (`float`, *optional*, defaults to 1e-12):
74
- The epsilon used by the rms normalization layers.
75
- use_cache (`bool`, *optional*, defaults to `True`):
76
- Whether or not the model should return the last key/values attentions (not used by all models). Only
77
- relevant if `config.is_decoder=True`.
78
- tie_word_embeddings(`bool`, *optional*, defaults to `False`):
79
- Whether to tie weight embeddings
80
- rope_theta (`float`, *optional*, defaults to 10000.0):
81
- The base period of the RoPE embeddings.
82
- rope_scaling (`Dict`, *optional*):
83
- Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
84
- strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
85
- is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
86
- `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
87
- these scaling strategies behave:
88
- https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
89
- experimental feature, subject to breaking API changes in future versions.
90
- attention_bias (`bool`, defaults to `False`):
91
- Whether to use a bias in the query, key, value and output projection layers during self-attention.
92
-
93
- Example:
94
-
95
- ```python
96
- >>> from transformers import LlamaModel, LlamaConfig
97
-
98
- >>> # Initializing a LLaMA llama-7b style configuration
99
- >>> configuration = LlamaConfig()
100
-
101
- >>> # Initializing a model from the llama-7b style configuration
102
- >>> model = LlamaModel(configuration)
103
-
104
- >>> # Accessing the model configuration
105
- >>> configuration = model.config
106
- ```"""
107
- model_type = "llama"
108
- keys_to_ignore_at_inference = ["past_key_values"]
109
-
110
- def __init__(
111
- self,
112
- vocab_size=32000,
113
- hidden_size=4096,
114
- intermediate_size=11008,
115
- num_hidden_layers=32,
116
- num_attention_heads=32,
117
- num_key_value_heads=None,
118
- hidden_act="silu",
119
- max_position_embeddings=2048,
120
- initializer_range=0.02,
121
- rms_norm_eps=1e-6,
122
- use_cache=True,
123
- pad_token_id=None,
124
- bos_token_id=1,
125
- eos_token_id=2,
126
- pretraining_tp=1,
127
- tie_word_embeddings=False,
128
- rope_theta=10000.0,
129
- rope_scaling=None,
130
- attention_bias=False,
131
- **kwargs,
132
- ):
133
- self.vocab_size = vocab_size
134
- self.max_position_embeddings = max_position_embeddings
135
- self.hidden_size = hidden_size
136
- self.intermediate_size = intermediate_size
137
- self.num_hidden_layers = num_hidden_layers
138
- self.num_attention_heads = num_attention_heads
139
-
140
- # for backward compatibility
141
- if num_key_value_heads is None:
142
- num_key_value_heads = num_attention_heads
143
-
144
- self.num_key_value_heads = num_key_value_heads
145
- self.hidden_act = hidden_act
146
- self.initializer_range = initializer_range
147
- self.rms_norm_eps = rms_norm_eps
148
- self.pretraining_tp = pretraining_tp
149
- self.use_cache = use_cache
150
- self.rope_theta = rope_theta
151
- self.rope_scaling = rope_scaling
152
- self._rope_scaling_validation()
153
- self.attention_bias = attention_bias
154
-
155
- super().__init__(
156
- pad_token_id=pad_token_id,
157
- bos_token_id=bos_token_id,
158
- eos_token_id=eos_token_id,
159
- tie_word_embeddings=tie_word_embeddings,
160
- **kwargs,
161
- )
162
-
163
- def _rope_scaling_validation(self):
164
- """
165
- Validate the `rope_scaling` configuration.
166
- """
167
- if self.rope_scaling is None:
168
- return
169
-
170
- if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
171
- raise ValueError(
172
- "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
173
- f"got {self.rope_scaling}"
174
- )
175
- rope_scaling_type = self.rope_scaling.get("type", None)
176
- rope_scaling_factor = self.rope_scaling.get("factor", None)
177
- if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
178
- raise ValueError(
179
- f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
180
- )
181
- if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
182
- raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/llama/convert_llama_weights_to_hf.py DELETED
@@ -1,318 +0,0 @@
1
- # Copyright 2022 EleutherAI and The HuggingFace Inc. team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- import argparse
15
- import gc
16
- import json
17
- import os
18
- import shutil
19
- import warnings
20
-
21
- import torch
22
-
23
- from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
24
-
25
-
26
- try:
27
- from transformers import LlamaTokenizerFast
28
- except ImportError as e:
29
- warnings.warn(e)
30
- warnings.warn(
31
- "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
32
- )
33
- LlamaTokenizerFast = None
34
-
35
- """
36
- Sample usage:
37
-
38
- ```
39
- python src/transformers/models/llama/convert_llama_weights_to_hf.py \
40
- --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path
41
- ```
42
-
43
- Thereafter, models can be loaded via:
44
-
45
- ```py
46
- from transformers import LlamaForCausalLM, LlamaTokenizer
47
-
48
- model = LlamaForCausalLM.from_pretrained("/output/path")
49
- tokenizer = LlamaTokenizer.from_pretrained("/output/path")
50
- ```
51
-
52
- Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
53
- come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
54
- """
55
-
56
- NUM_SHARDS = {
57
- "7B": 1,
58
- "7Bf": 1,
59
- "13B": 2,
60
- "13Bf": 2,
61
- "34B": 4,
62
- "30B": 4,
63
- "65B": 8,
64
- "70B": 8,
65
- "70Bf": 8,
66
- }
67
-
68
-
69
- def compute_intermediate_size(n, ffn_dim_multiplier=1, multiple_of=256):
70
- return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3)) + multiple_of - 1) // multiple_of)
71
-
72
-
73
- def read_json(path):
74
- with open(path, "r") as f:
75
- return json.load(f)
76
-
77
-
78
- def write_json(text, path):
79
- with open(path, "w") as f:
80
- json.dump(text, f)
81
-
82
-
83
- def write_model(model_path, input_base_path, model_size, tokenizer_path=None, safe_serialization=True):
84
- # for backward compatibility, before you needed the repo to be called `my_repo/model_size`
85
- if not os.path.isfile(os.path.join(input_base_path, "params.json")):
86
- input_base_path = os.path.join(input_base_path, model_size)
87
-
88
- os.makedirs(model_path, exist_ok=True)
89
- tmp_model_path = os.path.join(model_path, "tmp")
90
- os.makedirs(tmp_model_path, exist_ok=True)
91
-
92
- params = read_json(os.path.join(input_base_path, "params.json"))
93
- num_shards = NUM_SHARDS[model_size]
94
- n_layers = params["n_layers"]
95
- n_heads = params["n_heads"]
96
- n_heads_per_shard = n_heads // num_shards
97
- dim = params["dim"]
98
- dims_per_head = dim // n_heads
99
- base = params.get("rope_theta", 10000.0)
100
- inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
101
- if base > 10000.0:
102
- max_position_embeddings = 16384
103
- else:
104
- max_position_embeddings = 2048
105
-
106
- tokenizer_class = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
107
- if tokenizer_path is not None:
108
- tokenizer = tokenizer_class(tokenizer_path)
109
- tokenizer.save_pretrained(model_path)
110
- vocab_size = tokenizer.vocab_size if tokenizer_path is not None else 32000
111
-
112
- if "n_kv_heads" in params:
113
- num_key_value_heads = params["n_kv_heads"] # for GQA / MQA
114
- num_local_key_value_heads = n_heads_per_shard // num_key_value_heads
115
- key_value_dim = dim // num_key_value_heads
116
- else: # compatibility with other checkpoints
117
- num_key_value_heads = n_heads
118
- num_local_key_value_heads = n_heads_per_shard
119
- key_value_dim = dim
120
-
121
- # permute for sliced rotary
122
- def permute(w, n_heads=n_heads, dim1=dim, dim2=dim):
123
- return w.view(n_heads, dim1 // n_heads // 2, 2, dim2).transpose(1, 2).reshape(dim1, dim2)
124
-
125
- print(f"Fetching all parameters from the checkpoint at {input_base_path}.")
126
- # Load weights
127
- if model_size == "7B":
128
- # Not sharded
129
- # (The sharded implementation would also work, but this is simpler.)
130
- loaded = torch.load(os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu")
131
- else:
132
- # Sharded
133
- loaded = [
134
- torch.load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"), map_location="cpu")
135
- for i in range(num_shards)
136
- ]
137
- param_count = 0
138
- index_dict = {"weight_map": {}}
139
- for layer_i in range(n_layers):
140
- filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
141
- if model_size == "7B":
142
- # Unsharded
143
- state_dict = {
144
- f"model.layers.{layer_i}.self_attn.q_proj.weight": permute(
145
- loaded[f"layers.{layer_i}.attention.wq.weight"]
146
- ),
147
- f"model.layers.{layer_i}.self_attn.k_proj.weight": permute(
148
- loaded[f"layers.{layer_i}.attention.wk.weight"]
149
- ),
150
- f"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[f"layers.{layer_i}.attention.wv.weight"],
151
- f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[f"layers.{layer_i}.attention.wo.weight"],
152
- f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w1.weight"],
153
- f"model.layers.{layer_i}.mlp.down_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w2.weight"],
154
- f"model.layers.{layer_i}.mlp.up_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w3.weight"],
155
- f"model.layers.{layer_i}.input_layernorm.weight": loaded[f"layers.{layer_i}.attention_norm.weight"],
156
- f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[f"layers.{layer_i}.ffn_norm.weight"],
157
- }
158
- else:
159
- # Sharded
160
- # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
161
- # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
162
- # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
163
-
164
- state_dict = {
165
- f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
166
- f"layers.{layer_i}.attention_norm.weight"
167
- ].clone(),
168
- f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
169
- f"layers.{layer_i}.ffn_norm.weight"
170
- ].clone(),
171
- }
172
- state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
173
- torch.cat(
174
- [
175
- loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
176
- for i in range(num_shards)
177
- ],
178
- dim=0,
179
- ).reshape(dim, dim)
180
- )
181
- state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
182
- torch.cat(
183
- [
184
- loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(
185
- num_local_key_value_heads, dims_per_head, dim
186
- )
187
- for i in range(num_shards)
188
- ],
189
- dim=0,
190
- ).reshape(key_value_dim, dim),
191
- num_key_value_heads,
192
- key_value_dim,
193
- dim,
194
- )
195
- state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
196
- [
197
- loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(
198
- num_local_key_value_heads, dims_per_head, dim
199
- )
200
- for i in range(num_shards)
201
- ],
202
- dim=0,
203
- ).reshape(key_value_dim, dim)
204
-
205
- state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
206
- [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(num_shards)], dim=1
207
- )
208
- state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat(
209
- [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(num_shards)], dim=0
210
- )
211
- state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat(
212
- [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(num_shards)], dim=1
213
- )
214
- state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat(
215
- [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(num_shards)], dim=0
216
- )
217
-
218
- state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
219
- for k, v in state_dict.items():
220
- index_dict["weight_map"][k] = filename
221
- param_count += v.numel()
222
- torch.save(state_dict, os.path.join(tmp_model_path, filename))
223
-
224
- filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
225
- if model_size == "7B":
226
- # Unsharded
227
- state_dict = {
228
- "model.embed_tokens.weight": loaded["tok_embeddings.weight"],
229
- "model.norm.weight": loaded["norm.weight"],
230
- "lm_head.weight": loaded["output.weight"],
231
- }
232
- else:
233
- state_dict = {
234
- "model.norm.weight": loaded[0]["norm.weight"],
235
- "model.embed_tokens.weight": torch.cat(
236
- [loaded[i]["tok_embeddings.weight"] for i in range(num_shards)], dim=1
237
- ),
238
- "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(num_shards)], dim=0),
239
- }
240
-
241
- for k, v in state_dict.items():
242
- index_dict["weight_map"][k] = filename
243
- param_count += v.numel()
244
- torch.save(state_dict, os.path.join(tmp_model_path, filename))
245
-
246
- # Write configs
247
- index_dict["metadata"] = {"total_size": param_count * 2}
248
- write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
249
- ffn_dim_multiplier = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1
250
- multiple_of = params["multiple_of"] if "multiple_of" in params else 256
251
- config = LlamaConfig(
252
- hidden_size=dim,
253
- intermediate_size=compute_intermediate_size(dim, ffn_dim_multiplier, multiple_of),
254
- num_attention_heads=params["n_heads"],
255
- num_hidden_layers=params["n_layers"],
256
- rms_norm_eps=params["norm_eps"],
257
- num_key_value_heads=num_key_value_heads,
258
- vocab_size=vocab_size,
259
- rope_theta=base,
260
- max_position_embeddings=max_position_embeddings,
261
- )
262
- config.save_pretrained(tmp_model_path)
263
-
264
- # Make space so we can load the model properly now.
265
- del state_dict
266
- del loaded
267
- gc.collect()
268
-
269
- print("Loading the checkpoint in a Llama model.")
270
- model = LlamaForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
271
- # Avoid saving this as part of the config.
272
- del model.config._name_or_path
273
- model.config.torch_dtype = torch.float16
274
- print("Saving in the Transformers format.")
275
- model.save_pretrained(model_path, safe_serialization=safe_serialization)
276
- shutil.rmtree(tmp_model_path)
277
-
278
-
279
- def write_tokenizer(tokenizer_path, input_tokenizer_path):
280
- # Initialize the tokenizer based on the `spm` model
281
- tokenizer_class = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
282
- print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.")
283
- tokenizer = tokenizer_class(input_tokenizer_path)
284
- tokenizer.save_pretrained(tokenizer_path)
285
-
286
-
287
- def main():
288
- parser = argparse.ArgumentParser()
289
- parser.add_argument(
290
- "--input_dir",
291
- help="Location of LLaMA weights, which contains tokenizer.model and model folders",
292
- )
293
- parser.add_argument(
294
- "--model_size",
295
- choices=["7B", "7Bf", "13B", "13Bf", "30B", "34B", "65B", "70B", "70Bf", "tokenizer_only"],
296
- help="'f' models correspond to the finetuned versions, and are specific to the Llama2 official release. For more details on Llama2, checkout the original repo: https://huggingface.co/meta-llama",
297
- )
298
- parser.add_argument(
299
- "--output_dir",
300
- help="Location to write HF model and tokenizer",
301
- )
302
- parser.add_argument("--safe_serialization", type=bool, help="Whether or not to save using `safetensors`.")
303
- args = parser.parse_args()
304
- spm_path = os.path.join(args.input_dir, "tokenizer.model")
305
- if args.model_size != "tokenizer_only":
306
- write_model(
307
- model_path=args.output_dir,
308
- input_base_path=args.input_dir,
309
- model_size=args.model_size,
310
- safe_serialization=args.safe_serialization,
311
- tokenizer_path=spm_path,
312
- )
313
- else:
314
- write_tokenizer(args.output_dir, spm_path)
315
-
316
-
317
- if __name__ == "__main__":
318
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/llama/modeling_llama.py DELETED
@@ -1,1246 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
- #
4
- # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
- # and OPT implementations in this library. It has been modified from its
6
- # original forms to accommodate minor architectural differences compared
7
- # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
- #
9
- # Licensed under the Apache License, Version 2.0 (the "License");
10
- # you may not use this file except in compliance with the License.
11
- # You may obtain a copy of the License at
12
- #
13
- # http://www.apache.org/licenses/LICENSE-2.0
14
- #
15
- # Unless required by applicable law or agreed to in writing, software
16
- # distributed under the License is distributed on an "AS IS" BASIS,
17
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
- # See the License for the specific language governing permissions and
19
- # limitations under the License.
20
- """ PyTorch LLaMA model."""
21
- import math
22
- from typing import List, Optional, Tuple, Union
23
-
24
- import torch
25
- import torch.nn.functional as F
26
- import torch.utils.checkpoint
27
- from torch import nn
28
- from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
-
30
- from transformers.activations import ACT2FN
31
- from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
32
- from transformers.modeling_utils import PreTrainedModel
33
- from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
34
- from transformers.utils import (
35
- add_start_docstrings,
36
- add_start_docstrings_to_model_forward,
37
- logging,
38
- replace_return_docstrings,
39
- )
40
- try:
41
- from transformers.utils import is_flash_attn_available
42
- except ImportError:
43
- from transformers.utils import is_flash_attn_2_available as is_flash_attn_available
44
- from .configuration_llama import LlamaConfig
45
-
46
-
47
- if is_flash_attn_available():
48
- from flash_attn import flash_attn_func, flash_attn_varlen_func
49
- from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
50
-
51
-
52
- logger = logging.get_logger(__name__)
53
-
54
- _CONFIG_FOR_DOC = "LlamaConfig"
55
-
56
-
57
- def _get_unpad_data(padding_mask):
58
- seqlens_in_batch = padding_mask.sum(dim=-1, dtype=torch.int32)
59
- indices = torch.nonzero(padding_mask.flatten(), as_tuple=False).flatten()
60
- max_seqlen_in_batch = seqlens_in_batch.max().item()
61
- cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
62
- return (
63
- indices,
64
- cu_seqlens,
65
- max_seqlen_in_batch,
66
- )
67
-
68
-
69
- # Copied from transformers.models.bart.modeling_bart._make_causal_mask
70
- def _make_causal_mask(
71
- input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
72
- ):
73
- """
74
- Make causal mask used for bi-directional self-attention.
75
- """
76
- bsz, tgt_len = input_ids_shape
77
- mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
78
- mask_cond = torch.arange(mask.size(-1), device=device)
79
- mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
80
- mask = mask.to(dtype)
81
-
82
- if past_key_values_length > 0:
83
- mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
84
- return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
85
-
86
-
87
- # Copied from transformers.models.bart.modeling_bart._expand_mask
88
- def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
89
- """
90
- Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
91
- """
92
- bsz, src_len = mask.size()
93
- tgt_len = tgt_len if tgt_len is not None else src_len
94
-
95
- expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
96
-
97
- inverted_mask = 1.0 - expanded_mask
98
-
99
- return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
100
-
101
-
102
- class LlamaRMSNorm(nn.Module):
103
- def __init__(self, hidden_size, eps=1e-6):
104
- """
105
- LlamaRMSNorm is equivalent to T5LayerNorm
106
- """
107
- super().__init__()
108
- self.weight = nn.Parameter(torch.ones(hidden_size))
109
- self.variance_epsilon = eps
110
-
111
- def forward(self, hidden_states):
112
- input_dtype = hidden_states.dtype
113
- hidden_states = hidden_states.to(torch.float32)
114
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
115
- hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
116
- return self.weight * hidden_states.to(input_dtype)
117
-
118
-
119
- ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
120
-
121
-
122
- class LlamaRotaryEmbedding(nn.Module):
123
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
124
- super().__init__()
125
-
126
- self.dim = dim
127
- self.max_position_embeddings = max_position_embeddings
128
- self.base = base
129
- inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
130
- self.register_buffer("inv_freq", inv_freq, persistent=False)
131
-
132
- # Build here to make `torch.jit.trace` work.
133
- self._set_cos_sin_cache(
134
- seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
135
- )
136
-
137
- def _set_cos_sin_cache(self, seq_len, device, dtype):
138
- self.max_seq_len_cached = seq_len
139
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
140
-
141
- freqs = torch.einsum("i,j->ij", t, self.inv_freq)
142
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
143
- emb = torch.cat((freqs, freqs), dim=-1)
144
- self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
145
- self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
146
-
147
- def forward(self, x, seq_len=None):
148
- # x: [bs, num_attention_heads, seq_len, head_size]
149
- if seq_len > self.max_seq_len_cached:
150
- self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
151
-
152
- return (
153
- self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
154
- self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
155
- )
156
-
157
-
158
- class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
159
- """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
160
-
161
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
162
- self.scaling_factor = scaling_factor
163
- super().__init__(dim, max_position_embeddings, base, device)
164
-
165
- def _set_cos_sin_cache(self, seq_len, device, dtype):
166
- self.max_seq_len_cached = seq_len
167
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
168
- t = t / self.scaling_factor
169
-
170
- freqs = torch.einsum("i,j->ij", t, self.inv_freq)
171
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
172
- emb = torch.cat((freqs, freqs), dim=-1)
173
- self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
174
- self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
175
-
176
-
177
- class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
178
- """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
179
-
180
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
181
- self.scaling_factor = scaling_factor
182
- super().__init__(dim, max_position_embeddings, base, device)
183
-
184
- def _set_cos_sin_cache(self, seq_len, device, dtype):
185
- self.max_seq_len_cached = seq_len
186
-
187
- if seq_len > self.max_position_embeddings:
188
- base = self.base * (
189
- (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
190
- ) ** (self.dim / (self.dim - 2))
191
- inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
192
- self.register_buffer("inv_freq", inv_freq, persistent=False)
193
-
194
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
195
-
196
- freqs = torch.einsum("i,j->ij", t, self.inv_freq)
197
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
198
- emb = torch.cat((freqs, freqs), dim=-1)
199
- self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
200
- self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
201
-
202
-
203
- def rotate_half(x):
204
- """Rotates half the hidden dims of the input."""
205
- x1 = x[..., : x.shape[-1] // 2]
206
- x2 = x[..., x.shape[-1] // 2 :]
207
- return torch.cat((-x2, x1), dim=-1)
208
-
209
-
210
- def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
211
- # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
212
- cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
213
- sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
214
- cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
215
- sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
216
- q_embed = (q * cos) + (rotate_half(q) * sin)
217
- k_embed = (k * cos) + (rotate_half(k) * sin)
218
- return q_embed, k_embed
219
-
220
-
221
- class LlamaMLP(nn.Module):
222
- def __init__(self, config):
223
- super().__init__()
224
- self.config = config
225
- self.hidden_size = config.hidden_size
226
- self.intermediate_size = config.intermediate_size
227
- self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
228
- self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
229
- self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
230
- self.act_fn = ACT2FN[config.hidden_act]
231
-
232
- def forward(self, x):
233
- if self.config.pretraining_tp > 1:
234
- slice = self.intermediate_size // self.config.pretraining_tp
235
- gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
236
- up_proj_slices = self.up_proj.weight.split(slice, dim=0)
237
- down_proj_slices = self.down_proj.weight.split(slice, dim=1)
238
-
239
- gate_proj = torch.cat(
240
- [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
241
- )
242
- up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
243
-
244
- intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
245
- down_proj = [
246
- F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
247
- ]
248
- down_proj = sum(down_proj)
249
- else:
250
- down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
251
-
252
- return down_proj
253
-
254
-
255
- def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
256
- """
257
- This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
258
- num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
259
- """
260
- batch, num_key_value_heads, slen, head_dim = hidden_states.shape
261
- if n_rep == 1:
262
- return hidden_states
263
- hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
264
- return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
265
-
266
-
267
- class LlamaAttention(nn.Module):
268
- """Multi-headed attention from 'Attention Is All You Need' paper"""
269
-
270
- def __init__(self, config: LlamaConfig):
271
- super().__init__()
272
- self.config = config
273
- self.hidden_size = config.hidden_size
274
- self.num_heads = config.num_attention_heads
275
- self.head_dim = self.hidden_size // self.num_heads
276
- self.num_key_value_heads = config.num_key_value_heads
277
- self.num_key_value_groups = self.num_heads // self.num_key_value_heads
278
- self.max_position_embeddings = config.max_position_embeddings
279
- self.rope_theta = config.rope_theta
280
-
281
- if (self.head_dim * self.num_heads) != self.hidden_size:
282
- raise ValueError(
283
- f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
284
- f" and `num_heads`: {self.num_heads})."
285
- )
286
- self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
287
- self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
288
- self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
289
- self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
290
- self._init_rope()
291
-
292
- def _init_rope(self):
293
- if self.config.rope_scaling is None:
294
- self.rotary_emb = LlamaRotaryEmbedding(
295
- self.head_dim,
296
- max_position_embeddings=self.max_position_embeddings,
297
- base=self.rope_theta,
298
- )
299
- else:
300
- scaling_type = self.config.rope_scaling["type"]
301
- scaling_factor = self.config.rope_scaling["factor"]
302
- if scaling_type == "linear":
303
- self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
304
- self.head_dim,
305
- max_position_embeddings=self.max_position_embeddings,
306
- scaling_factor=scaling_factor,
307
- base=self.rope_theta,
308
- )
309
- elif scaling_type == "dynamic":
310
- self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
311
- self.head_dim,
312
- max_position_embeddings=self.max_position_embeddings,
313
- scaling_factor=scaling_factor,
314
- base=self.rope_theta,
315
- )
316
- else:
317
- raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
318
-
319
- def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
320
- return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
321
-
322
- def forward(
323
- self,
324
- hidden_states: torch.Tensor,
325
- attention_mask: Optional[torch.Tensor] = None,
326
- position_ids: Optional[torch.LongTensor] = None,
327
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
328
- output_attentions: bool = False,
329
- use_cache: bool = False,
330
- padding_mask: Optional[torch.LongTensor] = None,
331
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
332
- bsz, q_len, _ = hidden_states.size()
333
-
334
- if self.config.pretraining_tp > 1:
335
- key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
336
- query_slices = self.q_proj.weight.split(
337
- (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
338
- )
339
- key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
340
- value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
341
-
342
- query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
343
- query_states = torch.cat(query_states, dim=-1)
344
-
345
- key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
346
- key_states = torch.cat(key_states, dim=-1)
347
-
348
- value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
349
- value_states = torch.cat(value_states, dim=-1)
350
-
351
- else:
352
- query_states = self.q_proj(hidden_states)
353
- key_states = self.k_proj(hidden_states)
354
- value_states = self.v_proj(hidden_states)
355
-
356
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
357
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
358
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
359
-
360
- kv_seq_len = key_states.shape[-2]
361
- if past_key_value is not None:
362
- kv_seq_len += past_key_value[0].shape[-2]
363
- cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
364
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
365
-
366
- if past_key_value is not None:
367
- # reuse k, v, self_attention
368
- key_states = torch.cat([past_key_value[0], key_states], dim=2)
369
- value_states = torch.cat([past_key_value[1], value_states], dim=2)
370
-
371
- past_key_value = (key_states, value_states) if use_cache else None
372
-
373
- key_states = repeat_kv(key_states, self.num_key_value_groups)
374
- value_states = repeat_kv(value_states, self.num_key_value_groups)
375
-
376
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
377
-
378
- if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
379
- raise ValueError(
380
- f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
381
- f" {attn_weights.size()}"
382
- )
383
-
384
- if attention_mask is not None:
385
- if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
386
- raise ValueError(
387
- f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
388
- )
389
- attn_weights = attn_weights + attention_mask
390
-
391
- # upcast attention to fp32
392
- attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
393
- attn_output = torch.matmul(attn_weights, value_states)
394
-
395
- if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
396
- raise ValueError(
397
- f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
398
- f" {attn_output.size()}"
399
- )
400
-
401
- attn_output = attn_output.transpose(1, 2).contiguous()
402
-
403
- attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
404
-
405
- if self.config.pretraining_tp > 1:
406
- attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
407
- o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
408
- attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
409
- else:
410
- attn_output = self.o_proj(attn_output)
411
-
412
- if not output_attentions:
413
- attn_weights = None
414
-
415
- return attn_output, attn_weights, past_key_value
416
-
417
-
418
- class LlamaFlashAttention2(LlamaAttention):
419
- """
420
- Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
421
- untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
422
- flash attention and deal with padding tokens in case the input contains any of them.
423
- """
424
-
425
- def forward(
426
- self,
427
- hidden_states: torch.Tensor,
428
- attention_mask: Optional[torch.Tensor] = None,
429
- position_ids: Optional[torch.LongTensor] = None,
430
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
431
- output_attentions: bool = False,
432
- use_cache: bool = False,
433
- padding_mask: Optional[torch.LongTensor] = None,
434
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
435
- # LlamaFlashAttention2 attention does not support output_attentions
436
- output_attentions = False
437
-
438
- bsz, q_len, _ = hidden_states.size()
439
-
440
- query_states = self.q_proj(hidden_states)
441
- key_states = self.k_proj(hidden_states)
442
- value_states = self.v_proj(hidden_states)
443
-
444
- # Flash attention requires the input to have the shape
445
- # batch_size x seq_length x head_dime x hidden_dim
446
- # therefore we just need to keep the original shape
447
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
448
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
449
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
450
-
451
- kv_seq_len = key_states.shape[-2]
452
- if past_key_value is not None:
453
- kv_seq_len += past_key_value[0].shape[-2]
454
-
455
- cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
456
-
457
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
458
-
459
- if past_key_value is not None:
460
- # reuse k, v, self_attention
461
- key_states = torch.cat([past_key_value[0], key_states], dim=2)
462
- value_states = torch.cat([past_key_value[1], value_states], dim=2)
463
-
464
- past_key_value = (key_states, value_states) if use_cache else None
465
-
466
- query_states = query_states.transpose(1, 2)
467
- key_states = key_states.transpose(1, 2)
468
- value_states = value_states.transpose(1, 2)
469
-
470
- # TODO: llama does not have dropout in the config??
471
- # It is recommended to use dropout with FA according to the docs
472
- # when training.
473
- dropout_rate = 0.0 # if not self.training else self.attn_dropout
474
-
475
- # In PEFT, usually we cast the layer norms in float32 for training stability reasons
476
- # therefore the input hidden states gets silently casted in float32. Hence, we need
477
- # cast them back in float16 just to be sure everything works as expected.
478
- # This might slowdown training & inference so it is recommended to not cast the LayerNorms
479
- # in fp32. (LlamaRMSNorm handles it correctly)
480
- input_dtype = query_states.dtype
481
- if input_dtype == torch.float32:
482
- logger.warning_once(
483
- "The input hidden states seems to be silently casted in float32, this might be related to"
484
- " the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
485
- " float16."
486
- )
487
-
488
- query_states = query_states.to(torch.float16)
489
- key_states = key_states.to(torch.float16)
490
- value_states = value_states.to(torch.float16)
491
-
492
- attn_output = self._flash_attention_forward(
493
- query_states, key_states, value_states, padding_mask, q_len, dropout=dropout_rate
494
- )
495
-
496
- attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
497
- attn_output = self.o_proj(attn_output)
498
-
499
- if not output_attentions:
500
- attn_weights = None
501
-
502
- return attn_output, attn_weights, past_key_value
503
-
504
- def _flash_attention_forward(
505
- self, query_states, key_states, value_states, padding_mask, query_length, dropout=0.0, softmax_scale=None
506
- ):
507
- """
508
- Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
509
- first unpad the input, then computes the attention scores and pad the final attention scores.
510
-
511
- Args:
512
- query_states (`torch.Tensor`):
513
- Input query states to be passed to Flash Attention API
514
- key_states (`torch.Tensor`):
515
- Input key states to be passed to Flash Attention API
516
- value_states (`torch.Tensor`):
517
- Input value states to be passed to Flash Attention API
518
- padding_mask (`torch.Tensor`):
519
- The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
520
- position of padding tokens and 1 for the position of non-padding tokens.
521
- dropout (`int`, *optional*):
522
- Attention dropout
523
- softmax_scale (`float`, *optional*):
524
- The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
525
- """
526
- # Contains at least one padding token in the sequence
527
- if padding_mask is not None:
528
- batch_size = query_states.shape[0]
529
- query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
530
- query_states, key_states, value_states, padding_mask, query_length
531
- )
532
-
533
- cu_seqlens_q, cu_seqlens_k = cu_seq_lens
534
- max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
535
-
536
- attn_output_unpad = flash_attn_varlen_func(
537
- query_states,
538
- key_states,
539
- value_states,
540
- cu_seqlens_q=cu_seqlens_q,
541
- cu_seqlens_k=cu_seqlens_k,
542
- max_seqlen_q=max_seqlen_in_batch_q,
543
- max_seqlen_k=max_seqlen_in_batch_k,
544
- dropout_p=dropout,
545
- softmax_scale=softmax_scale,
546
- causal=True,
547
- )
548
-
549
- attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
550
- else:
551
- attn_output = flash_attn_func(
552
- query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=True
553
- )
554
-
555
- return attn_output
556
-
557
- def _upad_input(self, query_layer, key_layer, value_layer, padding_mask, query_length):
558
- indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(padding_mask)
559
- batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
560
-
561
- key_layer = index_first_axis(
562
- key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
563
- )
564
- value_layer = index_first_axis(
565
- value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
566
- )
567
- if query_length == kv_seq_len:
568
- query_layer = index_first_axis(
569
- query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
570
- )
571
- cu_seqlens_q = cu_seqlens_k
572
- max_seqlen_in_batch_q = max_seqlen_in_batch_k
573
- indices_q = indices_k
574
- elif query_length == 1:
575
- max_seqlen_in_batch_q = 1
576
- cu_seqlens_q = torch.arange(
577
- batch_size + 1, dtype=torch.int32, device=query_layer.device
578
- ) # There is a memcpy here, that is very bad.
579
- indices_q = cu_seqlens_q[:-1]
580
- query_layer = query_layer.squeeze(1)
581
- else:
582
- # The -q_len: slice assumes left padding.
583
- padding_mask = padding_mask[:, -query_length:]
584
- query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, padding_mask)
585
-
586
- return (
587
- query_layer,
588
- key_layer,
589
- value_layer,
590
- indices_q,
591
- (cu_seqlens_q, cu_seqlens_k),
592
- (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
593
- )
594
-
595
-
596
- class LlamaDecoderLayer(nn.Module):
597
- def __init__(self, config: LlamaConfig):
598
- super().__init__()
599
- self.hidden_size = config.hidden_size
600
- self.self_attn = (
601
- LlamaAttention(config=config)
602
- if not getattr(config, "_flash_attn_2_enabled", False)
603
- else LlamaFlashAttention2(config=config)
604
- )
605
- self.mlp = LlamaMLP(config)
606
- self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
607
- self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
608
-
609
- def forward(
610
- self,
611
- hidden_states: torch.Tensor,
612
- attention_mask: Optional[torch.Tensor] = None,
613
- position_ids: Optional[torch.LongTensor] = None,
614
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
615
- output_attentions: Optional[bool] = False,
616
- use_cache: Optional[bool] = False,
617
- padding_mask: Optional[torch.LongTensor] = None,
618
- ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
619
- """
620
- Args:
621
- hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
622
- attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
623
- `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
624
- output_attentions (`bool`, *optional*):
625
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
626
- returned tensors for more detail.
627
- use_cache (`bool`, *optional*):
628
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
629
- (see `past_key_values`).
630
- past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
631
- """
632
-
633
- residual = hidden_states
634
-
635
- hidden_states = self.input_layernorm(hidden_states)
636
-
637
- # Self Attention
638
- hidden_states, self_attn_weights, present_key_value = self.self_attn(
639
- hidden_states=hidden_states,
640
- attention_mask=attention_mask,
641
- position_ids=position_ids,
642
- past_key_value=past_key_value,
643
- output_attentions=output_attentions,
644
- use_cache=use_cache,
645
- padding_mask=padding_mask,
646
- )
647
- hidden_states = residual + hidden_states
648
-
649
- # Fully Connected
650
- residual = hidden_states
651
- hidden_states = self.post_attention_layernorm(hidden_states)
652
- hidden_states = self.mlp(hidden_states)
653
- hidden_states = residual + hidden_states
654
-
655
- outputs = (hidden_states,)
656
-
657
- if output_attentions:
658
- outputs += (self_attn_weights,)
659
-
660
- if use_cache:
661
- outputs += (present_key_value,)
662
-
663
- return outputs
664
-
665
-
666
- LLAMA_START_DOCSTRING = r"""
667
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
668
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
669
- etc.)
670
-
671
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
672
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
673
- and behavior.
674
-
675
- Parameters:
676
- config ([`LlamaConfig`]):
677
- Model configuration class with all the parameters of the model. Initializing with a config file does not
678
- load the weights associated with the model, only the configuration. Check out the
679
- [`~PreTrainedModel.from_pretrained`] method to load the model weights.
680
- """
681
-
682
-
683
- @add_start_docstrings(
684
- "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
685
- LLAMA_START_DOCSTRING,
686
- )
687
- class LlamaPreTrainedModel(PreTrainedModel):
688
- config_class = LlamaConfig
689
- base_model_prefix = "model"
690
- supports_gradient_checkpointing = True
691
- _no_split_modules = ["LlamaDecoderLayer"]
692
- _skip_keys_device_placement = "past_key_values"
693
- _supports_flash_attn_2 = True
694
-
695
- def _init_weights(self, module):
696
- std = self.config.initializer_range
697
- if isinstance(module, nn.Linear):
698
- module.weight.data.normal_(mean=0.0, std=std)
699
- if module.bias is not None:
700
- module.bias.data.zero_()
701
- elif isinstance(module, nn.Embedding):
702
- module.weight.data.normal_(mean=0.0, std=std)
703
- if module.padding_idx is not None:
704
- module.weight.data[module.padding_idx].zero_()
705
-
706
- def _set_gradient_checkpointing(self, module, value=False):
707
- if isinstance(module, LlamaModel):
708
- module.gradient_checkpointing = value
709
-
710
-
711
- LLAMA_INPUTS_DOCSTRING = r"""
712
- Args:
713
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
714
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
715
- it.
716
-
717
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
718
- [`PreTrainedTokenizer.__call__`] for details.
719
-
720
- [What are input IDs?](../glossary#input-ids)
721
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
722
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
723
-
724
- - 1 for tokens that are **not masked**,
725
- - 0 for tokens that are **masked**.
726
-
727
- [What are attention masks?](../glossary#attention-mask)
728
-
729
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
730
- [`PreTrainedTokenizer.__call__`] for details.
731
-
732
- If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
733
- `past_key_values`).
734
-
735
- If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
736
- and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
737
- information on the default strategy.
738
-
739
- - 1 indicates the head is **not masked**,
740
- - 0 indicates the head is **masked**.
741
- position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
742
- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
743
- config.n_positions - 1]`.
744
-
745
- [What are position IDs?](../glossary#position-ids)
746
- past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
747
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
748
- `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
749
- `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
750
-
751
- Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
752
- blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
753
-
754
- If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
755
- have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
756
- of shape `(batch_size, sequence_length)`.
757
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
758
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
759
- is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
760
- model's internal embedding lookup matrix.
761
- use_cache (`bool`, *optional*):
762
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
763
- `past_key_values`).
764
- output_attentions (`bool`, *optional*):
765
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
766
- tensors for more detail.
767
- output_hidden_states (`bool`, *optional*):
768
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
769
- more detail.
770
- return_dict (`bool`, *optional*):
771
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
772
- """
773
-
774
-
775
- @add_start_docstrings(
776
- "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
777
- LLAMA_START_DOCSTRING,
778
- )
779
- class LlamaModel(LlamaPreTrainedModel):
780
- """
781
- Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
782
-
783
- Args:
784
- config: LlamaConfig
785
- """
786
-
787
- def __init__(self, config: LlamaConfig):
788
- super().__init__(config)
789
- self.padding_idx = config.pad_token_id
790
- self.vocab_size = config.vocab_size
791
-
792
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
793
- self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
794
- self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
795
-
796
- self.gradient_checkpointing = False
797
- # Initialize weights and apply final processing
798
- self.post_init()
799
-
800
- def get_input_embeddings(self):
801
- return self.embed_tokens
802
-
803
- def set_input_embeddings(self, value):
804
- self.embed_tokens = value
805
-
806
- # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
807
- def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
808
- # create causal mask
809
- # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
810
- combined_attention_mask = None
811
- if input_shape[-1] > 1:
812
- combined_attention_mask = _make_causal_mask(
813
- input_shape,
814
- inputs_embeds.dtype,
815
- device=inputs_embeds.device,
816
- past_key_values_length=past_key_values_length,
817
- )
818
-
819
- if attention_mask is not None:
820
- # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
821
- expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
822
- inputs_embeds.device
823
- )
824
- combined_attention_mask = (
825
- expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
826
- )
827
-
828
- return combined_attention_mask
829
-
830
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
831
- def forward(
832
- self,
833
- input_ids: torch.LongTensor = None,
834
- attention_mask: Optional[torch.Tensor] = None,
835
- position_ids: Optional[torch.LongTensor] = None,
836
- past_key_values: Optional[List[torch.FloatTensor]] = None,
837
- inputs_embeds: Optional[torch.FloatTensor] = None,
838
- use_cache: Optional[bool] = None,
839
- output_attentions: Optional[bool] = None,
840
- output_hidden_states: Optional[bool] = None,
841
- return_dict: Optional[bool] = None,
842
- ) -> Union[Tuple, BaseModelOutputWithPast]:
843
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
844
- output_hidden_states = (
845
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
846
- )
847
- use_cache = use_cache if use_cache is not None else self.config.use_cache
848
-
849
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
850
-
851
- # retrieve input_ids and inputs_embeds
852
- if input_ids is not None and inputs_embeds is not None:
853
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
854
- elif input_ids is not None:
855
- batch_size, seq_length = input_ids.shape
856
- elif inputs_embeds is not None:
857
- batch_size, seq_length, _ = inputs_embeds.shape
858
- else:
859
- raise ValueError("You have to specify either input_ids or inputs_embeds")
860
-
861
- seq_length_with_past = seq_length
862
- past_key_values_length = 0
863
-
864
- if past_key_values is not None:
865
- past_key_values_length = past_key_values[0][0].shape[2]
866
- seq_length_with_past = seq_length_with_past + past_key_values_length
867
-
868
- if position_ids is None:
869
- device = input_ids.device if input_ids is not None else inputs_embeds.device
870
- position_ids = torch.arange(
871
- past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
872
- )
873
- position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
874
- else:
875
- position_ids = position_ids.view(-1, seq_length).long()
876
-
877
- if inputs_embeds is None:
878
- inputs_embeds = self.embed_tokens(input_ids)
879
- # embed positions
880
- if attention_mask is None:
881
- attention_mask = torch.ones(
882
- (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
883
- )
884
- padding_mask = None
885
- else:
886
- if 0 in attention_mask:
887
- padding_mask = attention_mask
888
- else:
889
- padding_mask = None
890
-
891
- attention_mask = self._prepare_decoder_attention_mask(
892
- attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
893
- )
894
-
895
- hidden_states = inputs_embeds
896
-
897
- if self.gradient_checkpointing and self.training:
898
- if use_cache:
899
- logger.warning_once(
900
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
901
- )
902
- use_cache = False
903
-
904
- # decoder layers
905
- all_hidden_states = () if output_hidden_states else None
906
- all_self_attns = () if output_attentions else None
907
- next_decoder_cache = () if use_cache else None
908
-
909
- for idx, decoder_layer in enumerate(self.layers):
910
- if output_hidden_states:
911
- all_hidden_states += (hidden_states,)
912
-
913
- past_key_value = past_key_values[idx] if past_key_values is not None else None
914
-
915
- if self.gradient_checkpointing and self.training:
916
-
917
- def create_custom_forward(module):
918
- def custom_forward(*inputs):
919
- # None for past_key_value
920
- return module(*inputs, past_key_value, output_attentions, padding_mask=padding_mask)
921
-
922
- return custom_forward
923
-
924
- layer_outputs = torch.utils.checkpoint.checkpoint(
925
- create_custom_forward(decoder_layer), hidden_states, attention_mask, position_ids
926
- )
927
- else:
928
- layer_outputs = decoder_layer(
929
- hidden_states,
930
- attention_mask=attention_mask,
931
- position_ids=position_ids,
932
- past_key_value=past_key_value,
933
- output_attentions=output_attentions,
934
- use_cache=use_cache,
935
- padding_mask=padding_mask,
936
- )
937
-
938
- hidden_states = layer_outputs[0]
939
-
940
- if use_cache:
941
- next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
942
-
943
- if output_attentions:
944
- all_self_attns += (layer_outputs[1],)
945
-
946
- hidden_states = self.norm(hidden_states)
947
-
948
- # add hidden states from the last decoder layer
949
- if output_hidden_states:
950
- all_hidden_states += (hidden_states,)
951
-
952
- next_cache = next_decoder_cache if use_cache else None
953
- if not return_dict:
954
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
955
- return BaseModelOutputWithPast(
956
- last_hidden_state=hidden_states,
957
- past_key_values=next_cache,
958
- hidden_states=all_hidden_states,
959
- attentions=all_self_attns,
960
- )
961
-
962
-
963
- class LlamaForCausalLM(LlamaPreTrainedModel):
964
- _tied_weights_keys = ["lm_head.weight"]
965
-
966
- def __init__(self, config):
967
- super().__init__(config)
968
- self.model = LlamaModel(config)
969
- self.vocab_size = config.vocab_size
970
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
971
-
972
- # Initialize weights and apply final processing
973
- self.post_init()
974
-
975
- def get_input_embeddings(self):
976
- return self.model.embed_tokens
977
-
978
- def set_input_embeddings(self, value):
979
- self.model.embed_tokens = value
980
-
981
- def get_output_embeddings(self):
982
- return self.lm_head
983
-
984
- def set_output_embeddings(self, new_embeddings):
985
- self.lm_head = new_embeddings
986
-
987
- def set_decoder(self, decoder):
988
- self.model = decoder
989
-
990
- def get_decoder(self):
991
- return self.model
992
-
993
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
994
- @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
995
- def forward(
996
- self,
997
- input_ids: torch.LongTensor = None,
998
- attention_mask: Optional[torch.Tensor] = None,
999
- position_ids: Optional[torch.LongTensor] = None,
1000
- past_key_values: Optional[List[torch.FloatTensor]] = None,
1001
- inputs_embeds: Optional[torch.FloatTensor] = None,
1002
- labels: Optional[torch.LongTensor] = None,
1003
- use_cache: Optional[bool] = None,
1004
- output_attentions: Optional[bool] = None,
1005
- output_hidden_states: Optional[bool] = None,
1006
- return_dict: Optional[bool] = None,
1007
- ) -> Union[Tuple, CausalLMOutputWithPast]:
1008
- r"""
1009
- Args:
1010
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1011
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1012
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1013
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1014
-
1015
- Returns:
1016
-
1017
- Example:
1018
-
1019
- ```python
1020
- >>> from transformers import AutoTokenizer, LlamaForCausalLM
1021
-
1022
- >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1023
- >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1024
-
1025
- >>> prompt = "Hey, are you conscious? Can you talk to me?"
1026
- >>> inputs = tokenizer(prompt, return_tensors="pt")
1027
-
1028
- >>> # Generate
1029
- >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1030
- >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1031
- "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1032
- ```"""
1033
-
1034
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1035
- output_hidden_states = (
1036
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1037
- )
1038
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1039
-
1040
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1041
- outputs = self.model(
1042
- input_ids=input_ids,
1043
- attention_mask=attention_mask,
1044
- position_ids=position_ids,
1045
- past_key_values=past_key_values,
1046
- inputs_embeds=inputs_embeds,
1047
- use_cache=use_cache,
1048
- output_attentions=output_attentions,
1049
- output_hidden_states=output_hidden_states,
1050
- return_dict=return_dict,
1051
- )
1052
-
1053
- hidden_states = outputs[0]
1054
- if self.config.pretraining_tp > 1:
1055
- lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1056
- logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1057
- logits = torch.cat(logits, dim=-1)
1058
- else:
1059
- logits = self.lm_head(hidden_states)
1060
- logits = logits.float()
1061
-
1062
- loss = None
1063
- if labels is not None:
1064
- # Shift so that tokens < n predict n
1065
- shift_logits = logits[..., :-1, :].contiguous()
1066
- shift_labels = labels[..., 1:].contiguous()
1067
- # Flatten the tokens
1068
- loss_fct = CrossEntropyLoss()
1069
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
1070
- shift_labels = shift_labels.view(-1)
1071
- # Enable model parallelism
1072
- shift_labels = shift_labels.to(shift_logits.device)
1073
- loss = loss_fct(shift_logits, shift_labels)
1074
-
1075
- if not return_dict:
1076
- output = (logits,) + outputs[1:]
1077
- return (loss,) + output if loss is not None else output
1078
-
1079
- return CausalLMOutputWithPast(
1080
- loss=loss,
1081
- logits=logits,
1082
- past_key_values=outputs.past_key_values,
1083
- hidden_states=outputs.hidden_states,
1084
- attentions=outputs.attentions,
1085
- )
1086
-
1087
- def prepare_inputs_for_generation(
1088
- self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1089
- ):
1090
- if past_key_values:
1091
- input_ids = input_ids[:, -1:]
1092
-
1093
- position_ids = kwargs.get("position_ids", None)
1094
- if attention_mask is not None and position_ids is None:
1095
- # create position_ids on the fly for batch generation
1096
- position_ids = attention_mask.long().cumsum(-1) - 1
1097
- position_ids.masked_fill_(attention_mask == 0, 1)
1098
- if past_key_values:
1099
- position_ids = position_ids[:, -1].unsqueeze(-1)
1100
-
1101
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1102
- if inputs_embeds is not None and past_key_values is None:
1103
- model_inputs = {"inputs_embeds": inputs_embeds}
1104
- else:
1105
- model_inputs = {"input_ids": input_ids}
1106
-
1107
- model_inputs.update(
1108
- {
1109
- "position_ids": position_ids,
1110
- "past_key_values": past_key_values,
1111
- "use_cache": kwargs.get("use_cache"),
1112
- "attention_mask": attention_mask,
1113
- }
1114
- )
1115
- return model_inputs
1116
-
1117
- @staticmethod
1118
- def _reorder_cache(past_key_values, beam_idx):
1119
- reordered_past = ()
1120
- for layer_past in past_key_values:
1121
- reordered_past += (
1122
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1123
- )
1124
- return reordered_past
1125
-
1126
-
1127
- @add_start_docstrings(
1128
- """
1129
- The LLaMa Model transformer with a sequence classification head on top (linear layer).
1130
-
1131
- [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1132
- (e.g. GPT-2) do.
1133
-
1134
- Since it does classification on the last token, it requires to know the position of the last token. If a
1135
- `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1136
- no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1137
- padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1138
- each row of the batch).
1139
- """,
1140
- LLAMA_START_DOCSTRING,
1141
- )
1142
- class LlamaForSequenceClassification(LlamaPreTrainedModel):
1143
- def __init__(self, config):
1144
- super().__init__(config)
1145
- self.num_labels = config.num_labels
1146
- self.model = LlamaModel(config)
1147
- self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1148
-
1149
- # Initialize weights and apply final processing
1150
- self.post_init()
1151
-
1152
- def get_input_embeddings(self):
1153
- return self.model.embed_tokens
1154
-
1155
- def set_input_embeddings(self, value):
1156
- self.model.embed_tokens = value
1157
-
1158
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1159
- def forward(
1160
- self,
1161
- input_ids: torch.LongTensor = None,
1162
- attention_mask: Optional[torch.Tensor] = None,
1163
- position_ids: Optional[torch.LongTensor] = None,
1164
- past_key_values: Optional[List[torch.FloatTensor]] = None,
1165
- inputs_embeds: Optional[torch.FloatTensor] = None,
1166
- labels: Optional[torch.LongTensor] = None,
1167
- use_cache: Optional[bool] = None,
1168
- output_attentions: Optional[bool] = None,
1169
- output_hidden_states: Optional[bool] = None,
1170
- return_dict: Optional[bool] = None,
1171
- ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1172
- r"""
1173
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1174
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1175
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1176
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1177
- """
1178
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1179
-
1180
- transformer_outputs = self.model(
1181
- input_ids,
1182
- attention_mask=attention_mask,
1183
- position_ids=position_ids,
1184
- past_key_values=past_key_values,
1185
- inputs_embeds=inputs_embeds,
1186
- use_cache=use_cache,
1187
- output_attentions=output_attentions,
1188
- output_hidden_states=output_hidden_states,
1189
- return_dict=return_dict,
1190
- )
1191
- hidden_states = transformer_outputs[0]
1192
- logits = self.score(hidden_states)
1193
-
1194
- if input_ids is not None:
1195
- batch_size = input_ids.shape[0]
1196
- else:
1197
- batch_size = inputs_embeds.shape[0]
1198
-
1199
- if self.config.pad_token_id is None and batch_size != 1:
1200
- raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1201
- if self.config.pad_token_id is None:
1202
- sequence_lengths = -1
1203
- else:
1204
- if input_ids is not None:
1205
- sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
1206
- logits.device
1207
- )
1208
- else:
1209
- sequence_lengths = -1
1210
-
1211
- pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1212
-
1213
- loss = None
1214
- if labels is not None:
1215
- labels = labels.to(logits.device)
1216
- if self.config.problem_type is None:
1217
- if self.num_labels == 1:
1218
- self.config.problem_type = "regression"
1219
- elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1220
- self.config.problem_type = "single_label_classification"
1221
- else:
1222
- self.config.problem_type = "multi_label_classification"
1223
-
1224
- if self.config.problem_type == "regression":
1225
- loss_fct = MSELoss()
1226
- if self.num_labels == 1:
1227
- loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1228
- else:
1229
- loss = loss_fct(pooled_logits, labels)
1230
- elif self.config.problem_type == "single_label_classification":
1231
- loss_fct = CrossEntropyLoss()
1232
- loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1233
- elif self.config.problem_type == "multi_label_classification":
1234
- loss_fct = BCEWithLogitsLoss()
1235
- loss = loss_fct(pooled_logits, labels)
1236
- if not return_dict:
1237
- output = (pooled_logits,) + transformer_outputs[1:]
1238
- return ((loss,) + output) if loss is not None else output
1239
-
1240
- return SequenceClassifierOutputWithPast(
1241
- loss=loss,
1242
- logits=pooled_logits,
1243
- past_key_values=transformer_outputs.past_key_values,
1244
- hidden_states=transformer_outputs.hidden_states,
1245
- attentions=transformer_outputs.attentions,
1246
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/llama/tokenization_llama.py DELETED
@@ -1,426 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
- #
4
- # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
- # and OPT implementations in this library. It has been modified from its
6
- # original forms to accommodate minor architectural differences compared
7
- # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
- #
9
- # Licensed under the Apache License, Version 2.0 (the "License");
10
- # you may not use this file except in compliance with the License.
11
- # You may obtain a copy of the License at
12
- #
13
- # http://www.apache.org/licenses/LICENSE-2.0
14
- #
15
- # Unless required by applicable law or agreed to in writing, software
16
- # distributed under the License is distributed on an "AS IS" BASIS,
17
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
- # See the License for the specific language governing permissions and
19
- # limitations under the License.
20
-
21
- """Tokenization classes for LLaMA."""
22
- import os
23
- from shutil import copyfile
24
- from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
25
-
26
- import sentencepiece as spm
27
-
28
- from transformers.convert_slow_tokenizer import import_protobuf
29
- from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
30
- from transformers.utils import logging
31
-
32
-
33
- if TYPE_CHECKING:
34
- from transformers.tokenization_utils_base import TextInput
35
-
36
- logger = logging.get_logger(__name__)
37
-
38
- VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
39
-
40
- PRETRAINED_VOCAB_FILES_MAP = {
41
- "vocab_file": {
42
- "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model",
43
- },
44
- "tokenizer_file": {
45
- "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json",
46
- },
47
- }
48
- PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
49
- "hf-internal-testing/llama-tokenizer": 2048,
50
- }
51
- SPIECE_UNDERLINE = "▁"
52
-
53
- B_INST, E_INST = "[INST]", "[/INST]"
54
- B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
55
-
56
- # fmt: off
57
- DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
58
- answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
59
- that your responses are socially unbiased and positive in nature.
60
-
61
- If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
62
- correct. If you don't know the answer to a question, please don't share false information."""
63
- # fmt: on
64
-
65
-
66
- class LlamaTokenizer(PreTrainedTokenizer):
67
- """
68
- Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
69
- no padding token in the original model.
70
-
71
- Args:
72
- vocab_file (`str`):
73
- Path to the vocabulary file.
74
- legacy (`bool`, *optional*):
75
- Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
76
- and #25224 which includes fixes to properly handle tokens that appear after special tokens. A simple
77
- example:
78
-
79
- - `legacy=True`:
80
- ```python
81
- >>> from transformers import T5Tokenizer
82
-
83
- >>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=True)
84
- >>> tokenizer.encode("Hello <extra_id_0>.")
85
- [8774, 32099, 3, 5, 1]
86
- ```
87
- - `legacy=False`:
88
- ```python
89
- >>> from transformers import T5Tokenizer
90
-
91
- >>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=False)
92
- >>> tokenizer.encode("Hello <extra_id_0>.") # the extra space `[3]` is no longer here
93
- [8774, 32099, 5, 1]
94
- ```
95
- Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
96
-
97
- """
98
-
99
- vocab_files_names = VOCAB_FILES_NAMES
100
- pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
101
- max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
102
- model_input_names = ["input_ids", "attention_mask"]
103
-
104
- def __init__(
105
- self,
106
- vocab_file,
107
- unk_token="<unk>",
108
- bos_token="<s>",
109
- eos_token="</s>",
110
- pad_token=None,
111
- sp_model_kwargs: Optional[Dict[str, Any]] = None,
112
- add_bos_token=True,
113
- add_eos_token=False,
114
- clean_up_tokenization_spaces=False,
115
- use_default_system_prompt=True,
116
- spaces_between_special_tokens=False,
117
- legacy=None,
118
- **kwargs,
119
- ):
120
- self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
121
- bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
122
- eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
123
- unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
124
- pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
125
-
126
- if legacy is None:
127
- logger.warning_once(
128
- f"You are using the default legacy behaviour of the {self.__class__}. This is"
129
- " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
130
- " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
131
- " means, and thouroughly read the reason why this was added as explained in"
132
- " https://github.com/huggingface/transformers/pull/24565"
133
- )
134
- legacy = True
135
-
136
- self.legacy = legacy
137
- self.vocab_file = vocab_file
138
- self.add_bos_token = add_bos_token
139
- self.add_eos_token = add_eos_token
140
- self.use_default_system_prompt = use_default_system_prompt
141
- self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
142
-
143
- super().__init__(
144
- bos_token=bos_token,
145
- eos_token=eos_token,
146
- unk_token=unk_token,
147
- pad_token=pad_token,
148
- add_bos_token=add_bos_token,
149
- add_eos_token=add_eos_token,
150
- sp_model_kwargs=self.sp_model_kwargs,
151
- clean_up_tokenization_spaces=clean_up_tokenization_spaces,
152
- use_default_system_prompt=use_default_system_prompt,
153
- spaces_between_special_tokens=spaces_between_special_tokens,
154
- legacy=legacy,
155
- **kwargs,
156
- )
157
-
158
- @property
159
- def unk_token_length(self):
160
- return len(self.sp_model.encode(str(self.unk_token)))
161
-
162
- # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
163
- def get_spm_processor(self, from_slow=False):
164
- tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
165
- if self.legacy or from_slow: # no dependency on protobuf
166
- tokenizer.Load(self.vocab_file)
167
- return tokenizer
168
-
169
- with open(self.vocab_file, "rb") as f:
170
- sp_model = f.read()
171
- model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
172
- model = model_pb2.ModelProto.FromString(sp_model)
173
- normalizer_spec = model_pb2.NormalizerSpec()
174
- normalizer_spec.add_dummy_prefix = False
175
- model.normalizer_spec.MergeFrom(normalizer_spec)
176
- sp_model = model.SerializeToString()
177
- tokenizer.LoadFromSerializedProto(sp_model)
178
- return tokenizer
179
-
180
- def __getstate__(self):
181
- state = self.__dict__.copy()
182
- state["sp_model"] = None
183
- state["sp_model_proto"] = self.sp_model.serialized_model_proto()
184
- return state
185
-
186
- def __setstate__(self, d):
187
- self.__dict__ = d
188
- self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
189
- self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
190
-
191
- @property
192
- def vocab_size(self):
193
- """Returns vocab size"""
194
- return self.sp_model.get_piece_size()
195
-
196
- def get_vocab(self):
197
- """Returns vocab as a dict"""
198
- vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
199
- vocab.update(self.added_tokens_encoder)
200
- return vocab
201
-
202
- # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
203
- def tokenize(self, text: "TextInput", add_special_tokens=False, **kwargs) -> List[str]:
204
- """
205
- Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
206
- first token is special.
207
- """
208
- if self.legacy or len(text) == 0:
209
- return super().tokenize(text, **kwargs)
210
-
211
- tokens = super().tokenize(SPIECE_UNDERLINE + text.replace(SPIECE_UNDERLINE, " "), **kwargs)
212
-
213
- if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
214
- tokens = tokens[1:]
215
- return tokens
216
-
217
- # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
218
- def _tokenize(self, text, **kwargs):
219
- """
220
- Returns a tokenized string.
221
-
222
- We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
223
- SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
224
- `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
225
- `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
226
- `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
227
- """
228
- tokens = self.sp_model.encode(text, out_type=str)
229
- if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
230
- return tokens
231
-
232
- # 1. Encode string + prefix ex: "<unk> Hey"
233
- tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
234
- # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
235
- return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
236
-
237
- def _convert_token_to_id(self, token):
238
- """Converts a token (str) in an id using the vocab."""
239
- return self.sp_model.piece_to_id(token)
240
-
241
- def _convert_id_to_token(self, index):
242
- """Converts an index (integer) in a token (str) using the vocab."""
243
- token = self.sp_model.IdToPiece(index)
244
- return token
245
-
246
- def convert_tokens_to_string(self, tokens):
247
- """Converts a sequence of tokens (string) in a single string."""
248
- # since we manually add the prefix space, we have to remove it when decoding
249
- if tokens[0].startswith(SPIECE_UNDERLINE):
250
- tokens[0] = tokens[0][1:]
251
-
252
- current_sub_tokens = []
253
- out_string = ""
254
- prev_is_special = False
255
- for i, token in enumerate(tokens):
256
- # make sure that special tokens are not decoded using sentencepiece model
257
- if token in self.all_special_tokens:
258
- if not prev_is_special and i != 0 and self.legacy:
259
- out_string += " "
260
- out_string += self.sp_model.decode(current_sub_tokens) + token
261
- prev_is_special = True
262
- current_sub_tokens = []
263
- else:
264
- current_sub_tokens.append(token)
265
- prev_is_special = False
266
- out_string += self.sp_model.decode(current_sub_tokens)
267
- return out_string
268
-
269
- def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
270
- """
271
- Save the vocabulary and special tokens file to a directory.
272
-
273
- Args:
274
- save_directory (`str`):
275
- The directory in which to save the vocabulary.
276
-
277
- Returns:
278
- `Tuple(str)`: Paths to the files saved.
279
- """
280
- if not os.path.isdir(save_directory):
281
- logger.error(f"Vocabulary path ({save_directory}) should be a directory")
282
- return
283
- out_vocab_file = os.path.join(
284
- save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
285
- )
286
-
287
- if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
288
- copyfile(self.vocab_file, out_vocab_file)
289
- elif not os.path.isfile(self.vocab_file):
290
- with open(out_vocab_file, "wb") as fi:
291
- content_spiece_model = self.sp_model.serialized_model_proto()
292
- fi.write(content_spiece_model)
293
-
294
- return (out_vocab_file,)
295
-
296
- def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
297
- bos_token_id = [self.bos_token_id] if self.add_bos_token else []
298
- eos_token_id = [self.eos_token_id] if self.add_eos_token else []
299
-
300
- output = bos_token_id + token_ids_0 + eos_token_id
301
-
302
- if token_ids_1 is not None:
303
- output = output + bos_token_id + token_ids_1 + eos_token_id
304
-
305
- return output
306
-
307
- def get_special_tokens_mask(
308
- self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
309
- ) -> List[int]:
310
- """
311
- Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
312
- special tokens using the tokenizer `prepare_for_model` method.
313
-
314
- Args:
315
- token_ids_0 (`List[int]`):
316
- List of IDs.
317
- token_ids_1 (`List[int]`, *optional*):
318
- Optional second list of IDs for sequence pairs.
319
- already_has_special_tokens (`bool`, *optional*, defaults to `False`):
320
- Whether or not the token list is already formatted with special tokens for the model.
321
-
322
- Returns:
323
- `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
324
- """
325
- if already_has_special_tokens:
326
- return super().get_special_tokens_mask(
327
- token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
328
- )
329
-
330
- bos_token_id = [1] if self.add_bos_token else []
331
- eos_token_id = [1] if self.add_eos_token else []
332
-
333
- if token_ids_1 is None:
334
- return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
335
- return (
336
- bos_token_id
337
- + ([0] * len(token_ids_0))
338
- + eos_token_id
339
- + bos_token_id
340
- + ([0] * len(token_ids_1))
341
- + eos_token_id
342
- )
343
-
344
- def create_token_type_ids_from_sequences(
345
- self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
346
- ) -> List[int]:
347
- """
348
- Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
349
- sequence pair mask has the following format:
350
-
351
- ```
352
- 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
353
- | first sequence | second sequence |
354
- ```
355
-
356
- if token_ids_1 is None, only returns the first portion of the mask (0s).
357
-
358
- Args:
359
- token_ids_0 (`List[int]`):
360
- List of ids.
361
- token_ids_1 (`List[int]`, *optional*):
362
- Optional second list of IDs for sequence pairs.
363
-
364
- Returns:
365
- `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
366
- """
367
- bos_token_id = [self.bos_token_id] if self.add_bos_token else []
368
- eos_token_id = [self.eos_token_id] if self.add_eos_token else []
369
-
370
- output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
371
-
372
- if token_ids_1 is not None:
373
- output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
374
-
375
- return output
376
-
377
- @property
378
- def default_chat_template(self):
379
- """
380
- LLaMA uses [INST] and [/INST] to indicate user messages, and <<SYS>> and <</SYS>> to indicate system messages.
381
- Assistant messages do not have special tokens, because LLaMA chat models are generally trained with strict
382
- user/assistant/user/assistant message ordering, and so assistant messages can be identified from the ordering
383
- rather than needing special tokens. The system message is partly 'embedded' in the first user message, which
384
- results in an unusual token ordering when it is present. This template should definitely be changed if you wish
385
- to fine-tune a model with more flexible role ordering!
386
-
387
- The output should look something like:
388
-
389
- <bos>[INST] B_SYS SystemPrompt E_SYS Prompt [/INST] Answer <eos> <bos>[INST] Prompt [/INST] Answer <eos>
390
- <bos>[INST] Prompt [/INST]
391
- """
392
-
393
- template = (
394
- "{% if messages[0]['role'] == 'system' %}"
395
- "{% set loop_messages = messages[1:] %}" # Extract system message if it's present
396
- "{% set system_message = messages[0]['content'] %}"
397
- "{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}"
398
- "{% set loop_messages = messages %}" # Or use the default system message if the flag is set
399
- "{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}"
400
- "{% else %}"
401
- "{% set loop_messages = messages %}"
402
- "{% set system_message = false %}"
403
- "{% endif %}"
404
- "{% for message in loop_messages %}" # Loop over all non-system messages
405
- "{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}"
406
- "{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}"
407
- "{% endif %}"
408
- "{% if loop.index0 == 0 and system_message != false %}" # Embed system message in first message
409
- "{% set content = '<<SYS>>\\n' + system_message + '\\n<</SYS>>\\n\\n' + message['content'] %}"
410
- "{% else %}"
411
- "{% set content = message['content'] %}"
412
- "{% endif %}"
413
- "{% if message['role'] == 'user' %}" # After all of that, handle messages/roles in a fairly normal way
414
- "{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}"
415
- "{% elif message['role'] == 'system' %}"
416
- "{{ '<<SYS>>\\n' + content.strip() + '\\n<</SYS>>\\n\\n' }}"
417
- "{% elif message['role'] == 'assistant' %}"
418
- "{{ ' ' + content.strip() + ' ' + eos_token }}"
419
- "{% endif %}"
420
- "{% endfor %}"
421
- )
422
- template = template.replace("USE_DEFAULT_PROMPT", "true" if self.use_default_system_prompt else "false")
423
- default_message = DEFAULT_SYSTEM_PROMPT.replace("\n", "\\n").replace("'", "\\'")
424
- template = template.replace("DEFAULT_SYSTEM_MESSAGE", default_message)
425
-
426
- return template
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/llama/tokenization_llama_fast.py DELETED
@@ -1,264 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2020 The HuggingFace Inc. team.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
- import os
16
- from shutil import copyfile
17
- from typing import Optional, Tuple
18
-
19
- from tokenizers import processors
20
-
21
- from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
22
- from transformers.utils import is_sentencepiece_available, logging
23
- from transformers.utils.versions import require_version
24
-
25
-
26
- require_version("tokenizers>=0.13.3")
27
-
28
- if is_sentencepiece_available():
29
- from .tokenization_llama import LlamaTokenizer
30
- else:
31
- LlamaTokenizer = None
32
-
33
- logger = logging.get_logger(__name__)
34
- VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}
35
-
36
- PRETRAINED_VOCAB_FILES_MAP = {
37
- "vocab_file": {
38
- "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model",
39
- },
40
- "tokenizer_file": {
41
- "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json",
42
- },
43
- }
44
- B_INST, E_INST = "[INST]", "[/INST]"
45
- B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
46
-
47
- # fmt: off
48
- DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
49
- answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
50
- that your responses are socially unbiased and positive in nature.
51
-
52
- If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
53
- correct. If you don't know the answer to a question, please don't share false information."""
54
- # fmt: on
55
-
56
-
57
- class LlamaTokenizerFast(PreTrainedTokenizerFast):
58
- """
59
- Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.
60
-
61
- This uses notably ByteFallback and no normalization.
62
-
63
- ```
64
- from transformers import LlamaTokenizerFast
65
-
66
- tokenizer = LlamaTokenizerFast.from_pretrained("hf-internal-testing/llama-tokenizer")
67
- tokenizer.encode("Hello this is a test")
68
- >>> [1, 15043, 445, 338, 263, 1243]
69
- ```
70
-
71
- If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
72
- call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
73
- values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
74
- [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
75
-
76
-
77
- This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
78
- refer to this superclass for more information regarding those methods.
79
-
80
- Args:
81
- vocab_file (`str`):
82
- [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .model extension) that
83
- contains the vocabulary necessary to instantiate a tokenizer.
84
- tokenizer_file (`str`):
85
- [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
86
- contains everything needed to load the tokenizer.
87
-
88
- clean_up_tokenization_spaces (`str`, *optional*, defaults to `False`):
89
- Wether to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra
90
- spaces.
91
-
92
- bos_token (`str`, *optional*, defaults to `"<s>"`):
93
- The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
94
-
95
- eos_token (`str`, *optional*, defaults to `"</s>"`):
96
- The end of sequence token.
97
-
98
- unk_token (`str`, *optional*, defaults to `"<unk>"`):
99
- The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
100
- token instead.
101
- """
102
-
103
- vocab_files_names = VOCAB_FILES_NAMES
104
- pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
105
- slow_tokenizer_class = LlamaTokenizer
106
- padding_side = "left"
107
- model_input_names = ["input_ids", "attention_mask"]
108
-
109
- def __init__(
110
- self,
111
- vocab_file=None,
112
- tokenizer_file=None,
113
- clean_up_tokenization_spaces=False,
114
- unk_token="<unk>",
115
- bos_token="<s>",
116
- eos_token="</s>",
117
- add_bos_token=True,
118
- add_eos_token=False,
119
- use_default_system_prompt=True,
120
- **kwargs,
121
- ):
122
- super().__init__(
123
- vocab_file=vocab_file,
124
- tokenizer_file=tokenizer_file,
125
- clean_up_tokenization_spaces=clean_up_tokenization_spaces,
126
- unk_token=unk_token,
127
- bos_token=bos_token,
128
- eos_token=eos_token,
129
- use_default_system_prompt=use_default_system_prompt,
130
- **kwargs,
131
- )
132
- self._add_bos_token = add_bos_token
133
- self._add_eos_token = add_eos_token
134
- self.update_post_processor()
135
- self.use_default_system_prompt = use_default_system_prompt
136
- self.vocab_file = vocab_file
137
-
138
- @property
139
- def can_save_slow_tokenizer(self) -> bool:
140
- return os.path.isfile(self.vocab_file) if self.vocab_file else False
141
-
142
- def update_post_processor(self):
143
- """
144
- Updates the underlying post processor with the current `bos_token` and `eos_token`.
145
- """
146
- bos = self.bos_token
147
- bos_token_id = self.bos_token_id
148
-
149
- eos = self.eos_token
150
- eos_token_id = self.eos_token_id
151
-
152
- single = f"{(bos+':0 ') * self.add_bos_token}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
153
- pair = f"{single}{(' '+bos+':1') * self.add_bos_token} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
154
-
155
- special_tokens = []
156
- if self.add_bos_token:
157
- special_tokens.append((bos, bos_token_id))
158
- if self.add_eos_token:
159
- special_tokens.append((eos, eos_token_id))
160
- self._tokenizer.post_processor = processors.TemplateProcessing(
161
- single=single, pair=pair, special_tokens=special_tokens
162
- )
163
-
164
- @property
165
- def add_eos_token(self):
166
- return self._add_eos_token
167
-
168
- @property
169
- def add_bos_token(self):
170
- return self._add_bos_token
171
-
172
- @add_eos_token.setter
173
- def add_eos_token(self, value):
174
- self._add_eos_token = value
175
- self.update_post_processor()
176
-
177
- @add_bos_token.setter
178
- def add_bos_token(self, value):
179
- self._add_bos_token = value
180
- self.update_post_processor()
181
-
182
- def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
183
- if not self.can_save_slow_tokenizer:
184
- raise ValueError(
185
- "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
186
- "tokenizer."
187
- )
188
-
189
- if not os.path.isdir(save_directory):
190
- logger.error(f"Vocabulary path ({save_directory}) should be a directory")
191
- return
192
- out_vocab_file = os.path.join(
193
- save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
194
- )
195
-
196
- if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
197
- copyfile(self.vocab_file, out_vocab_file)
198
-
199
- return (out_vocab_file,)
200
-
201
- @property
202
- # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.default_chat_template
203
- def default_chat_template(self):
204
- """
205
- LLaMA uses [INST] and [/INST] to indicate user messages, and <<SYS>> and <</SYS>> to indicate system messages.
206
- Assistant messages do not have special tokens, because LLaMA chat models are generally trained with strict
207
- user/assistant/user/assistant message ordering, and so assistant messages can be identified from the ordering
208
- rather than needing special tokens. The system message is partly 'embedded' in the first user message, which
209
- results in an unusual token ordering when it is present. This template should definitely be changed if you wish
210
- to fine-tune a model with more flexible role ordering!
211
-
212
- The output should look something like:
213
-
214
- <bos>[INST] B_SYS SystemPrompt E_SYS Prompt [/INST] Answer <eos> <bos>[INST] Prompt [/INST] Answer <eos>
215
- <bos>[INST] Prompt [/INST]
216
- """
217
-
218
- template = (
219
- "{% if messages[0]['role'] == 'system' %}"
220
- "{% set loop_messages = messages[1:] %}" # Extract system message if it's present
221
- "{% set system_message = messages[0]['content'] %}"
222
- "{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}"
223
- "{% set loop_messages = messages %}" # Or use the default system message if the flag is set
224
- "{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}"
225
- "{% else %}"
226
- "{% set loop_messages = messages %}"
227
- "{% set system_message = false %}"
228
- "{% endif %}"
229
- "{% for message in loop_messages %}" # Loop over all non-system messages
230
- "{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}"
231
- "{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}"
232
- "{% endif %}"
233
- "{% if loop.index0 == 0 and system_message != false %}" # Embed system message in first message
234
- "{% set content = '<<SYS>>\\n' + system_message + '\\n<</SYS>>\\n\\n' + message['content'] %}"
235
- "{% else %}"
236
- "{% set content = message['content'] %}"
237
- "{% endif %}"
238
- "{% if message['role'] == 'user' %}" # After all of that, handle messages/roles in a fairly normal way
239
- "{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}"
240
- "{% elif message['role'] == 'system' %}"
241
- "{{ '<<SYS>>\\n' + content.strip() + '\\n<</SYS>>\\n\\n' }}"
242
- "{% elif message['role'] == 'assistant' %}"
243
- "{{ ' ' + content.strip() + ' ' + eos_token }}"
244
- "{% endif %}"
245
- "{% endfor %}"
246
- )
247
- template = template.replace("USE_DEFAULT_PROMPT", "true" if self.use_default_system_prompt else "false")
248
- default_message = DEFAULT_SYSTEM_PROMPT.replace("\n", "\\n").replace("'", "\\'")
249
- template = template.replace("DEFAULT_SYSTEM_MESSAGE", default_message)
250
-
251
- return template
252
-
253
- # TODO ArthurZ let's rely on the template processor instead, refactor all fast tokenizers
254
- # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.build_inputs_with_special_tokens
255
- def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
256
- bos_token_id = [self.bos_token_id] if self.add_bos_token else []
257
- eos_token_id = [self.eos_token_id] if self.add_eos_token else []
258
-
259
- output = bos_token_id + token_ids_0 + eos_token_id
260
-
261
- if token_ids_1 is not None:
262
- output = output + bos_token_id + token_ids_1 + eos_token_id
263
-
264
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/models/lm_levo.py DELETED
@@ -1,540 +0,0 @@
1
-
2
- import torch
3
- import math
4
- import random
5
- import torch.nn as nn
6
- import typing as tp
7
- import torch.nn.functional as F
8
- from tqdm import tqdm
9
- from dataclasses import dataclass
10
- from codeclm.models.levo import CausalLM, LlamaConfig
11
- from codeclm.modules.streaming import StreamingModule
12
- from codeclm.modules.conditioners import (
13
- ConditioningAttributes,
14
- AudioCondition,
15
- ConditionType,
16
- ConditionerProvider,
17
- ConditionFuser,
18
- ClassifierFreeGuidanceDropoutInference,
19
- ClassifierFreeGuidanceDropout,
20
- AttributeDropout,
21
- )
22
- from codeclm.utils.utils import create_norm_fn, init_layer, sample_top_k, sample_top_p, multinomial
23
- from codeclm.modules.pattern import CodebooksPatternProvider
24
- ConditionTensors = tp.Dict[str, ConditionType]
25
-
26
- @dataclass
27
- class LMOutput:
28
- # The logits are already re-aligned with the input codes
29
- # hence no extra shift is required, e.g. when computing CE
30
- logits: torch.Tensor # [B, K, T, card]
31
- mask: torch.Tensor # [B, K, T]
32
-
33
-
34
- class LmModel(StreamingModule):
35
- """Transformer-based language model on multiple streams of codes.
36
-
37
- Args:
38
- pattern_provider (CodebooksPatternProvider): Pattern provider for codebook interleaving.
39
- condition_provider (ConditioningProvider): Conditioning provider from metadata.
40
- fuser (ConditionFuser): Fuser handling the fusing of conditions with language model input.
41
- code_depth (int): Number of parallel streams to model.
42
- code_size (int): Cardinality, vocabulary size.
43
- dim (int): Dimension of the transformer encoder.
44
- num_heads (int): Number of heads for the transformer encoder.
45
- hidden_scale (int): Scale for hidden feed forward dimension of the transformer encoder.
46
- norm (str): Normalization method.
47
- norm_first (bool): Use pre-norm instead of post-norm.
48
- emb_lr (float, optional): Embedding-specific learning rate.
49
- bias_proj (bool): Use bias for output projections.
50
- weight_init (str, optional): Method for weight initialization.
51
- depthwise_init (str, optional): Method for depthwise weight initialization.
52
- zero_bias_init (bool): If true and bias in Linears, initialize bias to zeros.
53
- cfg_dropout (float): Classifier-free guidance dropout.
54
- cfg_coef (float): Classifier-free guidance coefficient.
55
- attribute_dropout (dict): Attribute dropout probabilities.
56
- two_step_cfg (bool): Whether to run classifier free-guidance with 2 distinct steps.
57
- **kwargs: Additional parameters for the transformer encoder.
58
- """
59
- def __init__(self,
60
- pattern_provider: CodebooksPatternProvider,
61
- condition_provider: ConditionerProvider,
62
- fuser: ConditionFuser,
63
- code_depth: int = 8,
64
- code_size: int = 1024,
65
- dim: int = 128,
66
- intermediate_size: int = 4096,
67
- num_heads: int = 8,
68
- norm: str = 'layer_norm', norm_first: bool = False,
69
- weight_init: tp.Optional[str] = None, depthwise_init: tp.Optional[str] = None,
70
- zero_bias_init: bool = False, cfg_dropout: float = 0, cfg_coef: float = 1.0,
71
- attribute_dropout: tp.Dict[str, tp.Dict[str, float]] = {},
72
- num_layers=16,
73
- max_position_embeddings: int = 8196,
74
- max_position_embeddings_sub: int = 10000,
75
- rope_theta: float = 100000.0,
76
- rope_theta_sub: float = 500000.0,
77
- num_layers_sub: int = 12,
78
- cfg = None,
79
- use_flash_attn_2: bool = True,
80
- **kwargs):
81
- super().__init__()
82
-
83
- self.cfg_coef = cfg_coef
84
-
85
- self.cfg_dropout = ClassifierFreeGuidanceDropout(p=cfg_dropout,seed=random.randint(0, 9999))
86
- self.att_dropout = AttributeDropout(p=attribute_dropout,seed=random.randint(0, 9999))
87
- self.condition_provider = condition_provider
88
- self.fuser = fuser
89
- self.code_size = code_size + 1 # + EOS
90
- input_emb_dim = code_size + 2 # EOP
91
- self.code_depth = code_depth
92
- self.dim = dim
93
- self.cfg = cfg
94
- self.pattern_provider = pattern_provider
95
- self.emb = nn.ModuleList([nn.Embedding(input_emb_dim, dim)])
96
-
97
- model_cfg = LlamaConfig(
98
- hidden_size=dim,
99
- intermediate_size = intermediate_size,
100
- num_attention_heads = num_heads,
101
- num_hidden_layers = num_layers,
102
- num_key_value_heads = num_heads,
103
- vocab_size = self.code_size,
104
- use_cache=False,
105
- max_position_embeddings=max_position_embeddings,
106
- rms_norm_eps= 1e-5,
107
- rope_theta= rope_theta,
108
- _flash_attn_2_enabled=use_flash_attn_2,
109
- )
110
-
111
- self.transformer = CausalLM(model_cfg)
112
- self.mlp = nn.Sequential(
113
- nn.Linear(dim * 2, dim),
114
- nn.GELU(),
115
- nn.Linear(dim, dim)
116
- )
117
- self.layer2_emb = nn.ModuleList([nn.Embedding(input_emb_dim, dim)
118
- for _ in range(self.code_depth)])
119
- sub_model_cfg = LlamaConfig(
120
- hidden_size=dim,
121
- intermediate_size = intermediate_size,
122
- num_attention_heads = num_heads,
123
- num_hidden_layers = num_layers_sub,
124
- num_key_value_heads = num_heads,
125
- vocab_size = self.code_size,
126
- use_cache=False,
127
- max_position_embeddings=max_position_embeddings_sub,
128
- rms_norm_eps= 1e-5,
129
- rope_theta= rope_theta_sub,
130
- _flash_attn_2_enabled=use_flash_attn_2,
131
- )
132
-
133
- self.transformer2 = CausalLM(sub_model_cfg)
134
- self.out_norm: tp.Optional[nn.Module] = None
135
- if norm_first:
136
- self.out_norm = create_norm_fn(norm, dim)
137
- # enable EOS prediction
138
- if code_depth > 1:
139
- self.linears = nn.ModuleList([nn.Linear(dim, self.code_size, bias=False)
140
- for _ in range(code_depth - 1)])
141
-
142
- self._init_weights(weight_init, depthwise_init, zero_bias_init)
143
- self._fsdp: tp.Optional[nn.Module]
144
- self.__dict__['_fsdp'] = None
145
-
146
- self.reset_streaming()
147
-
148
- def _init_weights(self, weight_init: tp.Optional[str],
149
- depthwise_init: tp.Optional[str], zero_bias_init: bool):
150
- """Initialization of the transformer module weights.
151
-
152
- Args:
153
- weight_init (str, optional): Weight initialization strategy. See ``get_init_fn`` for valid options.
154
- depthwise_init (str, optional): Depthwise initialization strategy. The following options are valid:
155
- 'current' where the depth corresponds to the current layer index or 'global' where the total number
156
- of layer is used as depth. If not set, no depthwise initialization strategy is used.
157
- zero_bias_init (bool): Whether to initialize bias to zero or not.
158
- """
159
- assert depthwise_init is None or depthwise_init in ['current', 'global']
160
- assert depthwise_init is None or weight_init is not None, \
161
- "If 'depthwise_init' is defined, a 'weight_init' method should be provided."
162
- assert not zero_bias_init or weight_init is not None, \
163
- "If 'zero_bias_init', a 'weight_init' method should be provided"
164
-
165
- if weight_init is None:
166
- return
167
-
168
- for emb_layer in self.emb:
169
- init_layer(emb_layer, method=weight_init, init_depth=None, zero_bias_init=zero_bias_init)
170
-
171
-
172
- @property
173
- def special_token_id(self) -> int:
174
- return self.code_size # 10001
175
-
176
- @property
177
- def eos_token_id(self) -> int:
178
- return self.code_size-1 # 10000
179
-
180
- @torch.no_grad()
181
- def prepare_condition_tensors(self,
182
- batch_size = 1,
183
- text: tp.Optional[tp.List[str]] = None,
184
- descriptions: tp.Optional[tp.List[str]] = None,
185
- audio_qt_emb: tp.Optional[tp.List[torch.Tensor]] = None,
186
- prepare_null_condition = False,
187
- ):
188
- if self.training:
189
- attributes = []
190
- for i in range(batch_size):
191
- attr = ConditioningAttributes()
192
- if 'description' in self.condition_provider.conditioners:
193
- attr["text"]["description"] = ""
194
- if text is not None:
195
- attr["text"]["description"] = text[i]
196
- if 'prompt_audio' in self.condition_provider.conditioners:
197
- mask = (audio_qt_emb[[i], :, 0] == 16385).bool().unsqueeze(-1)
198
- audio_qt_seq = torch.cat([torch.full_like(audio_qt_emb[i][None][:,:,0], self.eos_token_id).unsqueeze(-1), audio_qt_emb[i][None]], dim=-1)
199
- mask = mask.repeat(1, 1, audio_qt_seq.shape[-1])
200
- audio_qt_seq[mask] = 16385
201
- attr["audio"]['prompt_audio'] = AudioCondition(
202
- wav=audio_qt_seq.long(),
203
- length=torch.Tensor([audio_qt_seq.shape[-1]]).long(),
204
- sample_rate=[self.cfg.sample_rate],)
205
- if 'type_info' in self.condition_provider.conditioners:
206
- attr["text"]["type_info"] = ""
207
- if descriptions is not None:
208
- attr["text"]["type_info"] = descriptions[i]
209
- attributes.append(attr)
210
- attributes = self.cfg_dropout(attributes) # drop ALL conditions
211
- attributes = self.att_dropout(attributes) # selectively drop some attributes (text, wav, or more fine-grained)
212
- tokenized = self.condition_provider.tokenize(attributes)
213
- condition_tensors = self.condition_provider(tokenized)
214
- else:
215
- conditions = []
216
- for i in range(batch_size):
217
- attr = ConditioningAttributes()
218
- if 'description' in self.condition_provider.conditioners:
219
- attr["text"]["description"] = ""
220
- if text is not None:
221
- attr["text"]["description"] = text[i]
222
- if 'prompt_audio' in self.condition_provider.conditioners:
223
- mask = (audio_qt_emb[[i], :, 0] == 16385).bool().unsqueeze(-1)
224
- audio_qt_seq = torch.cat([torch.full_like(audio_qt_emb[i][None][:,:,0], self.eos_token_id).unsqueeze(-1), audio_qt_emb[i][None]], dim=-1)
225
- mask = mask.repeat(1, 1, audio_qt_seq.shape[-1])
226
- audio_qt_seq[mask] = 16385
227
- attr["audio"]['prompt_audio'] = AudioCondition(
228
- wav=audio_qt_seq.long().cuda(),
229
- length=torch.Tensor([audio_qt_seq.shape[-1]]).long(),
230
- sample_rate=[self.cfg.sample_rate],)
231
- if 'type_info' in self.condition_provider.conditioners:
232
- attr["text"]["type_info"] = ""
233
- if descriptions is not None:
234
- attr["text"]["type_info"] = descriptions[i]
235
- conditions.append(attr)
236
- print("conditions", conditions)
237
- if prepare_null_condition:
238
- cfg_inference = ClassifierFreeGuidanceDropoutInference()
239
- null_conditions = cfg_inference(conditions, condition_types=["audio", "text"],
240
- customized=None)
241
- conditions = conditions + null_conditions
242
- tokenized_conditions = self.condition_provider.tokenize(conditions)
243
- condition_tensors = self.condition_provider(tokenized_conditions)
244
- return condition_tensors
245
-
246
- def forward(self,
247
- sequence: torch.Tensor,
248
- condition_tensors: ConditionTensors) -> torch.Tensor:
249
- """Apply language model on sequence and conditions.
250
- Given a tensor of sequence of shape [B, K, S] with K the number of codebooks and
251
- S the sequence steps, return the logits with shape [B, card, K, S].
252
-
253
- Args:
254
- indices (torch.Tensor): Indices of the codes to model.
255
- condition_tensors (dict[str, ConditionType], optional): Pre-computed conditioning
256
- tensors, see `conditions`.
257
- Returns:
258
- torch.Tensor: Logits.
259
- """
260
-
261
- # import pdb; pdb.set_trace()
262
- B, K, S = sequence.shape
263
- assert K == self.code_depth, "Sequence shape must match the specified number of codebooks"
264
- input_1 = self.emb[0](sequence[:, 0])
265
- input_2 = sum([self.layer2_emb[k](sequence[:, k]) for k in range(1, K)])
266
- fused_input1, fused_input2 = self.fuser(input_1, input_2, condition_tensors)
267
- output = self.transformer(inputs_embeds=fused_input1,
268
- use_cache=self._is_streaming,
269
- past_key_values=self._streaming_state.get('past_key_values_1', None))
270
- if self._is_streaming:
271
- self._streaming_state['past_key_values_1'] = output.past_key_values
272
- logits = output.logits # [B, S, card]
273
- logits = logits.unsqueeze(1) # [B, 1, S, card]
274
-
275
- # if self.out_norm:
276
- # out = self.out_norm(out.to(self.out_norm.weight.data.dtype))
277
- if K > 1:
278
- fused_input2 = torch.cat([fused_input2, output.hidden_states], dim=-1)
279
- fused_input2 = self.mlp(fused_input2)
280
- output2 = self.transformer2(inputs_embeds=fused_input2,
281
- use_cache=self._is_streaming,
282
- past_key_values=self._streaming_state.get('past_key_values_2', None))
283
- if self._is_streaming:
284
- self._streaming_state['past_key_values_2'] = output2.past_key_values
285
-
286
- res_logits = torch.stack([self.linears[k](output2.hidden_states) for k in range(K - 1)], dim=1) # [B, K, S, card] # [B, K, S, card]
287
- logits = torch.cat([logits, res_logits], dim=1) # [B, K, S, card]
288
-
289
- # remove the prefix from the model outputs
290
- if len(self.fuser.fuse2cond['prepend']) > 0:
291
- logits = logits[:, :, -S:, :]
292
-
293
- return logits # [B, K, S, card]
294
-
295
- def compute_predictions(self,
296
- codes: torch.Tensor,
297
- condition_tensors: tp.Optional[ConditionTensors] = None,
298
- **kwargs,
299
- ): # this function is called during training
300
- """Given an input tensor of codes [B, K, T] and list of conditions, runs the model
301
- forward using the specified codes interleaving pattern.
302
-
303
- Args:
304
- codes (torch.Tensor): Input codes of shape [B, K, T] with B the batch size,
305
- K the number of codebooks and T the number of timesteps.
306
- condition_tensors (dict[str, ConditionType], optional): pre-computed conditioning
307
- tensors, see `conditions`.
308
- Returns:
309
- LMOutput: Language model outputs
310
- logits (torch.Tensor) of shape [B, K, T, card] corresponding to the provided codes,
311
- i.e. the first item corresponds to logits to predict the first code, meaning that
312
- no additional shifting of codes and logits is required.
313
- mask (torch.Tensor) of shape [B, K, T], mask over valid and invalid positions.
314
- Given the specified interleaving strategies, parts of the logits and codes should
315
- not be considered as valid predictions because of invalid context.
316
- """
317
- B, K, T = codes.shape
318
- codes = codes.contiguous()
319
- # map codes [B, K, T] into pattern sequence [B, K, S] using special_token_id for masked tokens
320
- pattern = self.pattern_provider.get_pattern(T)
321
- sequence_codes, sequence_indexes, sequence_mask = pattern.build_pattern_sequence(
322
- codes, self.special_token_id, keep_only_valid_steps=False
323
- )
324
- model = self if self._fsdp is None else self._fsdp
325
- logits = model(sequence_codes, condition_tensors) # [B, K, S, card]
326
- # map back the logits on pattern sequence to logits on original codes: [B, K, S, card] -> [B, K, T, card]
327
- # and provide the corresponding mask over invalid positions of tokens
328
- logits = logits.permute(0, 3, 1, 2) # [B, card, K, S]
329
- # note: we use nans as special token to make it obvious if we feed unexpected logits
330
- logits, logits_indexes, logits_mask = pattern.revert_pattern_logits(
331
- logits, float('nan'), keep_only_valid_steps=False
332
- )
333
- logits = logits.permute(0, 2, 3, 1) # [B, K, T, card]
334
- logits_mask = logits_mask[None, :, :].expand(B, -1, -1) # [K, T] -> [B, K, T]
335
-
336
- return LMOutput(logits, logits_mask)
337
-
338
- @torch.no_grad()
339
- def generate(self, #
340
- # conditions: tp.List[ConditioningAttributes] = [],
341
- texts = None,
342
- descriptions = None,
343
- audio_qt_embs = None,
344
- num_samples: tp.Optional[int] = None,
345
- max_gen_len: int = 256,
346
- use_sampling: bool = True,
347
- temp: float = 1.0,
348
- top_k: int = 250,
349
- top_p: float = 0.0,
350
- cfg_coef: tp.Optional[float] = None,
351
- check: bool = False,
352
- record_tokens: bool = True,
353
- record_window: int = 150
354
- ) -> torch.Tensor:
355
- """Generate tokens sampling from the model given a prompt or unconditionally. Generation can
356
- be perform in a greedy fashion or using sampling with top K and top P strategies.
357
-
358
- Args:
359
- prompt (torch.Tensor, optional): Prompt tokens of shape [B, K, T].
360
- conditions_tensors (list of ConditioningAttributes, optional): List of conditions.
361
- num_samples (int, optional): Number of samples to generate when no prompt and no conditions are given.
362
- max_gen_len (int): Maximum generation length.
363
- use_sampling (bool): Whether to use a sampling strategy or not.
364
- temp (float): Sampling temperature.
365
- top_k (int): K for "top-k" sampling.
366
- top_p (float): P for "top-p" sampling.
367
- cfg_coeff (float, optional): Classifier-free guidance coefficient.
368
- check (bool): Whether to apply further checks on generated sequence.
369
- callback (Callback, optional): Callback function to report generation progress.
370
- Returns:
371
- torch.Tensor: Generated tokens.
372
- """
373
- assert not self.training, "generation shouldn't be used in training mode."
374
- first_param = next(iter(self.parameters()))
375
- device = first_param.device
376
-
377
- # 1) Check input shapes are consistent
378
- possible_num_samples = []
379
- if num_samples is not None:
380
- possible_num_samples.append(num_samples)
381
- elif texts:
382
- possible_num_samples.append(len(texts))
383
- elif audio_qt_embs:
384
- possible_num_samples.append(len(audio_qt_embs))
385
- else:
386
- possible_num_samples.append(1)
387
- assert [x == possible_num_samples[0] for x in possible_num_samples], "Inconsistent inputs shapes"
388
- num_samples = possible_num_samples[0]
389
- condition_tensors = self.prepare_condition_tensors(batch_size=1, text=texts, descriptions=descriptions, audio_qt_emb=audio_qt_embs, prepare_null_condition=True)
390
- # 3) Prepare token pool
391
- record_token_pool = None
392
- if record_tokens:
393
- record_token_pool = []
394
-
395
- # 4) set up startoff patterns
396
- start_offset = 0
397
- assert start_offset < max_gen_len, f"{start_offset}, {max_gen_len}"
398
- pattern = self.pattern_provider.get_pattern(max_gen_len)
399
- # this token is used as default value for codes that are not generated yet
400
- unknown_token = -1
401
- # we generate codes up to the max_gen_len that will be mapped to the pattern sequence
402
- B = num_samples
403
- gen_codes = torch.full((B, self.code_depth, max_gen_len),
404
- unknown_token, dtype=torch.long, device=device)
405
- # create the gen_sequence with proper interleaving from the pattern: [B, K, S]
406
- gen_sequence, indexes, mask = pattern.build_pattern_sequence(gen_codes, self.special_token_id)
407
- output_codes = torch.full_like(gen_sequence, self.code_size)
408
- # retrieve the start_offset in the sequence:
409
- # it is the first sequence step that contains the `start_offset` timestep
410
- start_offset_sequence = pattern.get_first_step_with_timesteps(start_offset)
411
- assert start_offset_sequence is not None
412
- is_end = torch.zeros((B, self.code_depth, 1)).bool().to(device)
413
- ignore_tokens = audio_qt_embs[0][0]
414
- ignore_tokens = ignore_tokens[ignore_tokens < 16384]
415
- # 5) auto-regressive sampling
416
- with self.streaming():
417
- gen_sequence_len = gen_sequence.shape[-1] # gen_sequence shape is [B, K, S]
418
- prev_offset = 0
419
- for offset in tqdm(range(start_offset_sequence, gen_sequence_len)):
420
- # get current sequence (note that the streaming API is providing the caching over previous offsets)
421
- curr_sequence = gen_sequence[..., prev_offset:offset]
422
- curr_mask = mask[None, ..., prev_offset:offset].expand(B, -1, -1)
423
- if check:
424
- # check coherence between mask and sequence
425
- assert (curr_sequence == torch.where(curr_mask, curr_sequence, self.special_token_id)).all()
426
- # should never happen as gen_sequence is filled progressively
427
- assert not (curr_sequence == unknown_token).any()
428
- # sample next token from the model, next token shape is [B, K, 1]
429
- next_token = self._sample_next_token(
430
- curr_sequence, condition_tensors, use_sampling, temp, top_k, top_p,
431
- cfg_coef=cfg_coef,
432
- sampled_token_pool=record_token_pool[-record_window:] if record_tokens else None,
433
- ignore_tokens = ignore_tokens
434
- )
435
- # ensure the tokens that should be masked are properly set to special_token_id
436
- # as the model never output special_token_id
437
- valid_mask = mask[..., offset:offset+1].expand(B, -1, -1)
438
- next_token[~valid_mask] = self.special_token_id
439
- # 检查eos id
440
- next_token[is_end] = self.special_token_id
441
- is_end = is_end | (next_token == self.eos_token_id)
442
- # ensure we don't overwrite prompt tokens, we only write over unknown tokens
443
- # (then mask tokens should be left as is as well, which is correct)
444
- gen_sequence[..., offset:offset+1] = torch.where(
445
- gen_sequence[..., offset:offset+1] == unknown_token,
446
- next_token, gen_sequence[..., offset:offset+1])
447
-
448
- # record sampled tokens in a window
449
- if record_tokens:
450
- record_token_pool.append(next_token.squeeze())
451
- if torch.all(is_end):
452
- gen_sequence = gen_sequence[..., :offset+1]
453
- break
454
- prev_offset = offset
455
-
456
- # ensure sequence has been entirely filled
457
- assert not (gen_sequence == unknown_token).any()
458
- max_gen_len = gen_sequence.shape[-1]
459
- output_codes[..., :max_gen_len] = gen_sequence
460
- # ensure gen_sequence pattern and mask are matching
461
- # which means the gen_sequence is valid according to the pattern
462
- # assert (gen_sequence == torch.where(mask[None, ...].expand(B, -1, -1), gen_sequence,
463
- # self.special_token_id)
464
- # ).all()
465
- # get back the codes, trimming the prompt if needed and cutting potentially incomplete timesteps
466
- out_codes, out_indexes, out_mask = pattern.revert_pattern_sequence(output_codes, special_token=unknown_token)
467
- # sanity checks over the returned codes and corresponding masks
468
- assert (out_codes != unknown_token).all()
469
- assert (out_mask == 1).all()
470
- # ensure the returned codes are all valid
471
- assert (out_codes >= 0).all() and (out_codes <= self.code_size).all()
472
- return out_codes
473
-
474
- def _sample_next_token(self,
475
- sequence: torch.Tensor,
476
- condition_tensors: ConditionTensors,
477
- use_sampling: bool = False,
478
- temp: float = 1.0,
479
- top_k: int = 0,
480
- top_p: float = 0.0,
481
- cfg_coef: tp.Optional[float] = None,
482
- sampled_token_pool: tp.Optional[list] = None,
483
- ignore_tokens: tp.Optional[torch.tensor] = torch.tensor([])) -> torch.Tensor:
484
- """Sample next token from the model given a sequence and a set of conditions. The model supports
485
- multiple sampling strategies (greedy sampling, softmax, top-k, top-p...).
486
-
487
- Args:
488
- sequence (torch.Tensor): Current sequence of shape [B, K, S]
489
- with K corresponding to the number of codebooks and S the number of sequence steps.
490
- S = 1 in streaming mode, except for the first step that contains a bigger prompt.
491
- condition_tensors (dict[str, ConditionType): Set of conditions. If CFG is used,
492
- should be twice the batch size, being the concatenation of the conditions + null conditions.
493
- use_sampling (bool): Whether to use a sampling strategy or not.
494
- temp (float): Sampling temperature.
495
- top_k (int): K for "top-k" sampling.
496
- top_p (float): P for "top-p" sampling.
497
- cfg_coef (float, optional): classifier free guidance coefficient
498
- Returns:
499
- next_token (torch.Tensor): Next token tensor of shape [B, K, 1].
500
- """
501
- # import pdb; pdb.set_trace()
502
- B = sequence.shape[0]
503
- cfg_coef = self.cfg_coef if cfg_coef is None else cfg_coef
504
- model = self if self._fsdp is None else self._fsdp
505
-
506
- # Preparing for CFG, predicting both conditional and unconditional logits.
507
- sequence = torch.cat([sequence, sequence], dim=0)
508
- all_logits = model(sequence, condition_tensors=condition_tensors)
509
- cond_logits, uncond_logits = all_logits.split(B, dim=0) # [B, K, T, card]
510
- logits = uncond_logits + (cond_logits - uncond_logits) * cfg_coef
511
-
512
- logits = logits.permute(0, 1, 3, 2) # [B, K, card, T]
513
- logits = logits[..., -1] # [B x K x card]
514
-
515
- # add punishment to pre-sampled tokens
516
- if sampled_token_pool is not None and len(sampled_token_pool) > 0:
517
- sampled_token_pool = torch.stack(sampled_token_pool, -1) # [K, T]
518
- for q in range(self.code_depth):
519
- # q_count = torch.bincount(sampled_token_pool)
520
- q_count = torch.bincount(torch.unique(sampled_token_pool[q]))
521
- tmp = min(q_count.shape[-1], self.code_size - 1)
522
- logits[:, q, :tmp] /= (1.1 ** q_count[:tmp])
523
-
524
- # Apply softmax for sampling if temp > 0. Else, do greedy sampling to avoid zero division error.
525
- if(ignore_tokens is not None and len(ignore_tokens) > 0):
526
- logits[0][0][ignore_tokens.to(torch.int)] = float('-inf')
527
- if use_sampling and temp > 0.0:
528
- probs = torch.softmax(logits / temp, dim=-1)
529
- if top_p > 0.0:
530
- next_token = sample_top_p(probs, p=top_p)
531
- elif top_k > 0:
532
- next_token_first = sample_top_k(probs[:,[0],:], k=top_k)
533
- next_token_res = sample_top_k(probs[:,1:,:], k=1)
534
- next_token = torch.cat([next_token_first,next_token_res], dim = 1)
535
- else:
536
- next_token = multinomial(probs, num_samples=1)
537
- else:
538
- next_token = torch.argmax(logits, dim=-1, keepdim=True)
539
-
540
- return next_token
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/modules/conditioners.py DELETED
@@ -1,718 +0,0 @@
1
-
2
- import typing as tp
3
- import torch
4
- import torch.nn as nn
5
- from dataclasses import dataclass, field, fields
6
- from itertools import chain
7
- import warnings
8
- import torch.nn.functional as F
9
- from torch.nn.utils.rnn import pad_sequence
10
- from codeclm.utils.utils import length_to_mask, collate
11
- from codeclm.modules.streaming import StreamingModule
12
- from collections import defaultdict
13
- from copy import deepcopy
14
- ConditionType = tp.Tuple[torch.Tensor, torch.Tensor] # condition, mask
15
-
16
- # ================================================================
17
- # Condition and Condition attributes definitions
18
- # ================================================================
19
- class AudioCondition(tp.NamedTuple):
20
- wav: torch.Tensor
21
- length: torch.Tensor
22
- sample_rate: tp.List[int]
23
- path: tp.List[tp.Optional[str]] = []
24
- seek_time: tp.List[tp.Optional[float]] = []
25
-
26
- @dataclass
27
- class ConditioningAttributes:
28
- text: tp.Dict[str, tp.Optional[str]] = field(default_factory=dict)
29
- audio: tp.Dict[str, AudioCondition] = field(default_factory=dict)
30
-
31
- def __getitem__(self, item):
32
- return getattr(self, item)
33
-
34
- @property
35
- def text_attributes(self):
36
- return self.text.keys()
37
-
38
- @property
39
- def audio_attributes(self):
40
- return self.audio.keys()
41
-
42
- @property
43
- def attributes(self):
44
- return {
45
- "text": self.text_attributes,
46
- "audio": self.audio_attributes,
47
- }
48
-
49
- def to_flat_dict(self):
50
- return {
51
- **{f"text.{k}": v for k, v in self.text.items()},
52
- **{f"audio.{k}": v for k, v in self.audio.items()},
53
- }
54
-
55
- @classmethod
56
- def from_flat_dict(cls, x):
57
- out = cls()
58
- for k, v in x.items():
59
- kind, att = k.split(".")
60
- out[kind][att] = v
61
- return out
62
-
63
- # ================================================================
64
- # Conditioner (tokenize and encode raw conditions) definitions
65
- # ================================================================
66
-
67
- class BaseConditioner(nn.Module):
68
- """Base model for all conditioner modules.
69
- We allow the output dim to be different than the hidden dim for two reasons:
70
- 1) keep our LUTs small when the vocab is large;
71
- 2) make all condition dims consistent.
72
-
73
- Args:
74
- dim (int): Hidden dim of the model.
75
- output_dim (int): Output dim of the conditioner.
76
- """
77
- def __init__(self, dim: int, output_dim: int, input_token = False, padding_idx=0):
78
- super().__init__()
79
- self.dim = dim
80
- self.output_dim = output_dim
81
- if input_token:
82
- self.output_proj = nn.Embedding(dim, output_dim, padding_idx)
83
- else:
84
- self.output_proj = nn.Linear(dim, output_dim)
85
-
86
- def tokenize(self, *args, **kwargs) -> tp.Any:
87
- """Should be any part of the processing that will lead to a synchronization
88
- point, e.g. BPE tokenization with transfer to the GPU.
89
-
90
- The returned value will be saved and return later when calling forward().
91
- """
92
- raise NotImplementedError()
93
-
94
- def forward(self, inputs: tp.Any) -> ConditionType:
95
- """Gets input that should be used as conditioning (e.g, genre, description or a waveform).
96
- Outputs a ConditionType, after the input data was embedded as a dense vector.
97
-
98
- Returns:
99
- ConditionType:
100
- - A tensor of size [B, T, D] where B is the batch size, T is the length of the
101
- output embedding and D is the dimension of the embedding.
102
- - And a mask indicating where the padding tokens.
103
- """
104
- raise NotImplementedError()
105
-
106
- class TextConditioner(BaseConditioner):
107
- ...
108
-
109
-
110
- class QwTokenizerConditioner(TextConditioner):
111
- def __init__(self, output_dim: int,
112
- token_path = "",
113
- max_len = 300,
114
- add_token_list=[]): #""
115
- add_token_list.append('.')
116
- from transformers import Qwen2Tokenizer
117
- self.text_tokenizer = Qwen2Tokenizer.from_pretrained(token_path)
118
- if add_token_list != []:
119
- self.text_tokenizer.add_tokens(add_token_list, special_tokens=True)
120
- voc_size = len(self.text_tokenizer.get_vocab())
121
- # here initialize a output_proj (nn.Embedding) layer
122
- super().__init__(voc_size, output_dim, input_token=True, padding_idx=151643)
123
- self.max_len = max_len
124
- self.padding_idx =' <|endoftext|>'
125
-
126
- vocab = self.text_tokenizer.get_vocab()
127
- # struct是全部的结构
128
- struct_tokens = [i for i in add_token_list if i[0]=='[' and i[-1]==']']
129
- self.struct_token_ids = [vocab[i] for i in struct_tokens]
130
- self.pad_token_idx = 151643
131
-
132
- self.structure_emb = nn.Embedding(200, output_dim, padding_idx=0)
133
- # self.split_token_id = vocab["."]
134
- print("all structure tokens: ", {self.text_tokenizer.convert_ids_to_tokens(i):i for i in self.struct_token_ids})
135
-
136
- def tokenize(self, x: tp.List[tp.Optional[str]]) -> tp.Dict[str, torch.Tensor]:
137
- x = ['<|im_start|>' + xi if xi is not None else "<|im_start|>" for xi in x]
138
- # x = [xi if xi is not None else "" for xi in x]
139
- inputs = self.text_tokenizer(x, return_tensors="pt", padding=True)
140
- return inputs
141
-
142
- def forward(self, inputs: tp.Dict[str, torch.Tensor]) -> ConditionType:
143
- """
144
- Add structure embeddings of {verse, chorus, bridge} to text/lyric tokens that
145
- belong to these structures accordingly,
146
- Then delete or keep these structure embeddings.
147
- """
148
- mask = inputs['attention_mask']
149
- tokens = inputs['input_ids']
150
- B = tokens.shape[0]
151
- is_sp_embed = torch.any(torch.stack([tokens == i for i in self.struct_token_ids], dim=-1),dim=-1)
152
-
153
- tp_cover_range = torch.zeros_like(tokens)
154
- for b, is_sp in enumerate(is_sp_embed):
155
- sp_list = torch.where(is_sp)[0].tolist()
156
- sp_list.append(mask[b].sum())
157
- for i, st in enumerate(sp_list[:-1]):
158
- tp_cover_range[b, st: sp_list[i+1]] = tokens[b, st] - 151645
159
-
160
- if self.max_len is not None:
161
- tokens = self.pad_2d_tensor(tokens, self.max_len, self.pad_token_idx).to(self.output_proj.weight.device)
162
- mask = self.pad_2d_tensor(mask, self.max_len, 0).to(self.output_proj.weight.device)
163
- tp_cover_range = self.pad_2d_tensor(tp_cover_range, self.max_len, 0).to(self.output_proj.weight.device)
164
- device = self.output_proj.weight.device
165
- content_embeds = self.output_proj(tokens.to(device))
166
- structure_embeds = self.structure_emb(tp_cover_range.to(device))
167
-
168
- embeds = content_embeds + structure_embeds
169
- return embeds, mask
170
-
171
- def pad_2d_tensor(self, x, max_len, pad_id):
172
- batch_size, seq_len = x.size()
173
- pad_len = max_len - seq_len
174
-
175
- if pad_len > 0:
176
- pad_tensor = torch.full((batch_size, pad_len), pad_id, dtype=x.dtype, device=x.device)
177
- padded_tensor = torch.cat([x, pad_tensor], dim=1)
178
- elif pad_len < 0:
179
- padded_tensor = x[:, :max_len]
180
- else:
181
- padded_tensor = x
182
-
183
- return padded_tensor
184
-
185
-
186
- class QwTextConditioner(TextConditioner):
187
- def __init__(self, output_dim: int,
188
- token_path = "",
189
- max_len = 300,
190
- version: str = 'v1.0'): #""
191
-
192
- from transformers import Qwen2Tokenizer
193
- self.text_tokenizer = Qwen2Tokenizer.from_pretrained(token_path)
194
- self.text_tokenizer.add_tokens(['[Musicality-very-high]', '[Musicality-high]', '[Musicality-medium]', '[Musicality-low]', '[Musicality-very-low]', '[Pure-Music]', '.'], special_tokens=True)
195
- print(self.text_tokenizer)
196
- voc_size = len(self.text_tokenizer.get_vocab())
197
- # here initialize a output_proj (nn.Embedding) layer
198
- super().__init__(voc_size, output_dim, input_token=True, padding_idx=151643)
199
-
200
- self.max_len = max_len
201
-
202
- def tokenize(self, x: tp.List[tp.Optional[str]]) -> tp.Dict[str, torch.Tensor]:
203
- x = ['<|im_start|>' + xi if xi is not None else "<|im_start|>" for xi in x]
204
- inputs = self.text_tokenizer(x, return_tensors="pt", padding=True)
205
- return inputs
206
-
207
- def forward(self, inputs: tp.Dict[str, torch.Tensor], structure_dur = None) -> ConditionType:
208
- """
209
- Add structure embeddings of {verse, chorus, bridge} to text/lyric tokens that
210
- belong to these structures accordingly,
211
- Then delete or keep these structure embeddings.
212
- """
213
- mask = inputs['attention_mask']
214
- tokens = inputs['input_ids']
215
-
216
- if self.max_len is not None:
217
- if inputs['input_ids'].shape[-1] > self.max_len:
218
- warnings.warn(f"Max len limit ({self.max_len}) Exceed! \
219
- {[self.text_tokenizer.convert_ids_to_tokens(i.tolist()) for i in tokens]} will be cut!")
220
- tokens = self.pad_2d_tensor(tokens, self.max_len, 151643).to(self.output_proj.weight.device)
221
- mask = self.pad_2d_tensor(mask, self.max_len, 0).to(self.output_proj.weight.device)
222
-
223
- embeds = self.output_proj(tokens)
224
- return embeds, mask
225
-
226
- def pad_2d_tensor(self, x, max_len, pad_id):
227
- batch_size, seq_len = x.size()
228
- pad_len = max_len - seq_len
229
-
230
- if pad_len > 0:
231
- pad_tensor = torch.full((batch_size, pad_len), pad_id, dtype=x.dtype, device=x.device)
232
- padded_tensor = torch.cat([x, pad_tensor], dim=1)
233
- elif pad_len < 0:
234
- padded_tensor = x[:, :max_len]
235
- else:
236
- padded_tensor = x
237
-
238
- return padded_tensor
239
-
240
-
241
- class AudioConditioner(BaseConditioner):
242
- ...
243
-
244
- class QuantizedEmbeddingConditioner(AudioConditioner):
245
- def __init__(self, dim: int,
246
- code_size: int,
247
- code_depth: int,
248
- max_len: int,
249
- **kwargs):
250
- super().__init__(dim, dim, input_token=True)
251
- self.code_depth = code_depth
252
- # add 1 for <s> token
253
- self.emb = nn.ModuleList([nn.Embedding(code_size+2, dim, padding_idx=code_size+1) for _ in range(code_depth)])
254
- # add End-Of-Text embedding
255
- self.EOT_emb = nn.Parameter(torch.randn(1, dim), requires_grad=True)
256
- self.output_proj = None
257
- self.max_len = max_len
258
- self.vocab_size = code_size
259
-
260
- def tokenize(self, x: AudioCondition) -> AudioCondition:
261
- """no extra ops"""
262
- # wav, length, sample_rate, path, seek_time = x
263
- # assert length is not None
264
- return x #AudioCondition(wav, length, sample_rate, path, seek_time)
265
-
266
- def forward(self, x: AudioCondition):
267
- wav, lengths, *_ = x
268
- B = wav.shape[0]
269
- wav = wav.reshape(B, self.code_depth, -1).long()
270
- if wav.shape[2] < self.max_len - 1:
271
- wav = F.pad(wav, [0, self.max_len - 1 - wav.shape[2]], value=self.vocab_size+1)
272
- else:
273
- wav = wav[:, :, :self.max_len-1]
274
- # self.emb.to(wav.device) # 都放cuda
275
- wav = wav.to(self.emb[0].weight.device)
276
- embeds = sum([self.emb[k](wav[:, k]) for k in range(self.code_depth)]) # B,T,D
277
- # self.EOT_emb.data = self.EOT_emb.data.to(embeds.device)
278
- embeds = torch.cat((self.EOT_emb.unsqueeze(0).repeat(B, 1, 1),
279
- embeds), dim=1)
280
- lengths = lengths + 1
281
- lengths = torch.clamp(lengths, max=self.max_len)
282
-
283
- if lengths is not None:
284
- mask = length_to_mask(lengths, max_len=embeds.shape[1]).int() # type: ignore
285
- else:
286
- mask = torch.ones((B, self.code_depth), device=embeds.device, dtype=torch.int)
287
- return embeds, mask
288
-
289
-
290
- # ================================================================
291
- # Aggregate all conditions and corresponding conditioners
292
- # ================================================================
293
- class ConditionerProvider(nn.Module):
294
- """Prepare and provide conditions given all the supported conditioners.
295
-
296
- Args:
297
- conditioners (dict): Dictionary of conditioners.
298
- device (torch.device or str, optional): Device for conditioners and output condition types.
299
- """
300
- def __init__(self, conditioners: tp.Dict[str, BaseConditioner]):
301
- super().__init__()
302
- self.conditioners = nn.ModuleDict(conditioners)
303
-
304
- @property
305
- def text_conditions(self):
306
- return [k for k, v in self.conditioners.items() if isinstance(v, TextConditioner)]
307
-
308
- @property
309
- def audio_conditions(self):
310
- return [k for k, v in self.conditioners.items() if isinstance(v, AudioConditioner)]
311
-
312
- @property
313
- def has_audio_condition(self):
314
- return len(self.audio_conditions) > 0
315
-
316
- def tokenize(self, inputs: tp.List[ConditioningAttributes]) -> tp.Dict[str, tp.Any]:
317
- """Match attributes/audios with existing conditioners in self, and compute tokenize them accordingly.
318
- This should be called before starting any real GPU work to avoid synchronization points.
319
- This will return a dict matching conditioner names to their arbitrary tokenized representations.
320
-
321
- Args:
322
- inputs (list[ConditioningAttributes]): List of ConditioningAttributes objects containing
323
- text and audio conditions.
324
- """
325
- assert all([isinstance(x, ConditioningAttributes) for x in inputs]), (
326
- "Got unexpected types input for conditioner! should be tp.List[ConditioningAttributes]",
327
- f" but types were {set([type(x) for x in inputs])}")
328
-
329
- output = {}
330
- text = self._collate_text(inputs)
331
- audios = self._collate_audios(inputs)
332
-
333
- assert set(text.keys() | audios.keys()).issubset(set(self.conditioners.keys())), (
334
- f"Got an unexpected attribute! Expected {self.conditioners.keys()}, ",
335
- f"got {text.keys(), audios.keys()}")
336
-
337
- for attribute, batch in chain(text.items(), audios.items()):
338
- output[attribute] = self.conditioners[attribute].tokenize(batch)
339
- return output
340
-
341
- def forward(self, tokenized: tp.Dict[str, tp.Any], structure_dur = None) -> tp.Dict[str, ConditionType]:
342
- """Compute pairs of `(embedding, mask)` using the configured conditioners and the tokenized representations.
343
- The output is for example:
344
- {
345
- "genre": (torch.Tensor([B, 1, D_genre]), torch.Tensor([B, 1])),
346
- "description": (torch.Tensor([B, T_desc, D_desc]), torch.Tensor([B, T_desc])),
347
- ...
348
- }
349
-
350
- Args:
351
- tokenized (dict): Dict of tokenized representations as returned by `tokenize()`.
352
- """
353
- output = {}
354
- for attribute, inputs in tokenized.items():
355
- if attribute == 'description' and structure_dur is not None:
356
- condition, mask = self.conditioners[attribute](inputs, structure_dur = structure_dur)
357
- else:
358
- condition, mask = self.conditioners[attribute](inputs)
359
- output[attribute] = (condition, mask)
360
- return output
361
-
362
- def _collate_text(self, samples: tp.List[ConditioningAttributes]) -> tp.Dict[str, tp.List[tp.Optional[str]]]:
363
- """Given a list of ConditioningAttributes objects, compile a dictionary where the keys
364
- are the attributes and the values are the aggregated input per attribute.
365
- For example:
366
- Input:
367
- [
368
- ConditioningAttributes(text={"genre": "Rock", "description": "A rock song with a guitar solo"}, wav=...),
369
- ConditioningAttributes(text={"genre": "Hip-hop", "description": "A hip-hop verse"}, audio=...),
370
- ]
371
- Output:
372
- {
373
- "genre": ["Rock", "Hip-hop"],
374
- "description": ["A rock song with a guitar solo", "A hip-hop verse"]
375
- }
376
-
377
- Args:
378
- samples (list of ConditioningAttributes): List of ConditioningAttributes samples.
379
- Returns:
380
- dict[str, list[str, optional]]: A dictionary mapping an attribute name to text batch.
381
- """
382
- out: tp.Dict[str, tp.List[tp.Optional[str]]] = defaultdict(list)
383
- texts = [x.text for x in samples]
384
- for text in texts:
385
- for condition in self.text_conditions:
386
- out[condition].append(text[condition])
387
- return out
388
-
389
- def _collate_audios(self, samples: tp.List[ConditioningAttributes]) -> tp.Dict[str, AudioCondition]:
390
- """Generate a dict where the keys are attributes by which we fetch similar audios,
391
- and the values are Tensors of audios according to said attributes.
392
-
393
- *Note*: by the time the samples reach this function, each sample should have some audios
394
- inside the "audio" attribute. It should be either:
395
- 1. A real audio
396
- 2. A null audio due to the sample having no similar audios (nullified by the dataset)
397
- 3. A null audio due to it being dropped in a dropout module (nullified by dropout)
398
-
399
- Args:
400
- samples (list of ConditioningAttributes): List of ConditioningAttributes samples.
401
- Returns:
402
- dict[str, WavCondition]: A dictionary mapping an attribute name to wavs.
403
- """
404
- # import pdb; pdb.set_trace()
405
- wavs = defaultdict(list)
406
- lengths = defaultdict(list)
407
- sample_rates = defaultdict(list)
408
- paths = defaultdict(list)
409
- seek_times = defaultdict(list)
410
- out: tp.Dict[str, AudioCondition] = {}
411
-
412
- for sample in samples:
413
- for attribute in self.audio_conditions:
414
- wav, length, sample_rate, path, seek_time = sample.audio[attribute]
415
- assert wav.dim() == 3, f"Got wav with dim={wav.dim()}, but expected 3 [1, C, T]"
416
- assert wav.size(0) == 1, f"Got wav [B, C, T] with shape={wav.shape}, but expected B == 1"
417
- wavs[attribute].append(wav.flatten()) # [C*T]
418
- lengths[attribute].append(length)
419
- sample_rates[attribute].extend(sample_rate)
420
- paths[attribute].extend(path)
421
- seek_times[attribute].extend(seek_time)
422
-
423
- # stack all wavs to a single tensor
424
- for attribute in self.audio_conditions:
425
- stacked_wav, _ = collate(wavs[attribute], dim=0)
426
- out[attribute] = AudioCondition(
427
- stacked_wav.unsqueeze(1),
428
- torch.cat(lengths[attribute]), sample_rates[attribute],
429
- paths[attribute], seek_times[attribute])
430
-
431
- return out
432
-
433
-
434
- class ConditionFuser(StreamingModule):
435
- """Condition fuser handles the logic to combine the different conditions
436
- to the actual model input.
437
-
438
- Args:
439
- fuse2cond (tp.Dict[str, str]): A dictionary that says how to fuse
440
- each condition. For example:
441
- {
442
- "prepend": ["description"],
443
- "sum": ["genre", "bpm"],
444
- }
445
- """
446
- FUSING_METHODS = ["sum", "prepend"] #, "cross", "input_interpolate"] (not support in this simplest version)
447
-
448
- def __init__(self, fuse2cond: tp.Dict[str, tp.List[str]]):
449
- super().__init__()
450
- assert all([k in self.FUSING_METHODS for k in fuse2cond.keys()]
451
- ), f"Got invalid fuse method, allowed methods: {self.FUSING_METHODS}"
452
- self.fuse2cond: tp.Dict[str, tp.List[str]] = fuse2cond
453
- self.cond2fuse: tp.Dict[str, str] = {}
454
- for fuse_method, conditions in fuse2cond.items():
455
- for condition in conditions:
456
- self.cond2fuse[condition] = fuse_method
457
-
458
- def forward(
459
- self,
460
- input: torch.Tensor,
461
- conditions: tp.Dict[str, ConditionType]
462
- ) -> tp.Tuple[torch.Tensor, tp.Optional[torch.Tensor]]:
463
- """Fuse the conditions to the provided model input.
464
-
465
- Args:
466
- input (torch.Tensor): Transformer input.
467
- conditions (dict[str, ConditionType]): Dict of conditions.
468
- Returns:
469
- tuple[torch.Tensor, torch.Tensor]: The first tensor is the transformer input
470
- after the conditions have been fused. The second output tensor is the tensor
471
- used for cross-attention or None if no cross attention inputs exist.
472
- """
473
- #import pdb; pdb.set_trace()
474
- B, T, _ = input.shape
475
-
476
- if 'offsets' in self._streaming_state:
477
- first_step = False
478
- offsets = self._streaming_state['offsets']
479
- else:
480
- first_step = True
481
- offsets = torch.zeros(input.shape[0], dtype=torch.long, device=input.device)
482
-
483
- assert set(conditions.keys()).issubset(set(self.cond2fuse.keys())), \
484
- f"given conditions contain unknown attributes for fuser, " \
485
- f"expected {self.cond2fuse.keys()}, got {conditions.keys()}"
486
-
487
- # if 'prepend' mode is used,
488
- # the concatenation order will be the SAME with the conditions in config:
489
- # prepend: ['description', 'prompt_audio'] (then goes the input)
490
- fused_input = input
491
- for fuse_op in self.fuse2cond.keys():
492
- fuse_op_conditions = self.fuse2cond[fuse_op]
493
- if fuse_op == 'sum' and len(fuse_op_conditions) > 0:
494
- for cond in fuse_op_conditions:
495
- this_cond, cond_mask = conditions[cond]
496
- fused_input += this_cond
497
- elif fuse_op == 'prepend' and len(fuse_op_conditions) > 0:
498
- if not first_step:
499
- continue
500
- reverse_list = deepcopy(fuse_op_conditions)
501
- reverse_list.reverse()
502
- for cond in reverse_list:
503
- this_cond, cond_mask = conditions[cond]
504
- fused_input = torch.cat((this_cond, fused_input), dim=1) # concat along T dim
505
- elif fuse_op not in self.FUSING_METHODS:
506
- raise ValueError(f"unknown op ({fuse_op})")
507
-
508
- if self._is_streaming:
509
- self._streaming_state['offsets'] = offsets + T
510
-
511
- return fused_input
512
-
513
-
514
-
515
- # ================================================================
516
- # Condition Dropout
517
- # ================================================================
518
- class DropoutModule(nn.Module):
519
- """Base module for all dropout modules."""
520
- def __init__(self, seed: int = 1234):
521
- super().__init__()
522
- self.rng = torch.Generator()
523
- self.rng.manual_seed(seed)
524
-
525
-
526
-
527
- class ClassifierFreeGuidanceDropout(DropoutModule):
528
- """Classifier Free Guidance dropout.
529
- All attributes are dropped with the same probability.
530
-
531
- Args:
532
- p (float): Probability to apply condition dropout during training.
533
- seed (int): Random seed.
534
- """
535
- def __init__(self, p: float, seed: int = 1234):
536
- super().__init__(seed=seed)
537
- self.p = p
538
-
539
- def check(self, sample, condition_type, condition):
540
-
541
- if condition_type not in ['text', 'audio']:
542
- raise ValueError("dropout_condition got an unexpected condition type!"
543
- f" expected 'text', 'audio' but got '{condition_type}'")
544
-
545
- if condition not in getattr(sample, condition_type):
546
- raise ValueError(
547
- "dropout_condition received an unexpected condition!"
548
- f" expected audio={sample.audio.keys()} and text={sample.text.keys()}"
549
- f" but got '{condition}' of type '{condition_type}'!")
550
-
551
-
552
- def get_null_wav(self, wav, sr=48000) -> AudioCondition:
553
- out = wav * 0 + 16385
554
- return AudioCondition(
555
- wav=out,
556
- length=torch.Tensor([0]).long(),
557
- sample_rate=[sr],)
558
-
559
- def dropout_condition(self,
560
- sample: ConditioningAttributes,
561
- condition_type: str,
562
- condition: str) -> ConditioningAttributes:
563
- """Utility function for nullifying an attribute inside an ConditioningAttributes object.
564
- If the condition is of type "wav", then nullify it using `nullify_condition` function.
565
- If the condition is of any other type, set its value to None.
566
- Works in-place.
567
- """
568
- self.check(sample, condition_type, condition)
569
-
570
- if condition_type == 'audio':
571
- audio_cond = sample.audio[condition]
572
- sample.audio[condition] = self.get_null_wav(audio_cond.wav, sr=audio_cond.sample_rate[0])
573
- else:
574
- sample.text[condition] = None
575
-
576
- return sample
577
-
578
- def forward(self, samples: tp.List[ConditioningAttributes]) -> tp.List[ConditioningAttributes]:
579
- """
580
- Args:
581
- samples (list[ConditioningAttributes]): List of conditions.
582
- Returns:
583
- list[ConditioningAttributes]: List of conditions after all attributes were set to None.
584
- """
585
- # decide on which attributes to drop in a batched fashion
586
- # drop = torch.rand(1, generator=self.rng).item() < self.p
587
- # if not drop:
588
- # return samples
589
-
590
- # nullify conditions of all attributes
591
- samples = deepcopy(samples)
592
-
593
- for sample in samples:
594
- drop = torch.rand(1, generator=self.rng).item()
595
- if drop<self.p:
596
- for condition_type in ["audio", "text"]:
597
- for condition in sample.attributes[condition_type]:
598
- self.dropout_condition(sample, condition_type, condition)
599
- return samples
600
-
601
- def __repr__(self):
602
- return f"ClassifierFreeGuidanceDropout(p={self.p})"
603
-
604
-
605
- class ClassifierFreeGuidanceDropoutInference(ClassifierFreeGuidanceDropout):
606
- """Classifier Free Guidance dropout during inference.
607
- All attributes are dropped with the same probability.
608
-
609
- Args:
610
- p (float): Probability to apply condition dropout during training.
611
- seed (int): Random seed.
612
- """
613
- def __init__(self, seed: int = 1234):
614
- super().__init__(p=1, seed=seed)
615
-
616
- def dropout_condition_customized(self,
617
- sample: ConditioningAttributes,
618
- condition_type: str,
619
- condition: str,
620
- customized: list = None) -> ConditioningAttributes:
621
- """Utility function for nullifying an attribute inside an ConditioningAttributes object.
622
- If the condition is of type "audio", then nullify it using `nullify_condition` function.
623
- If the condition is of any other type, set its value to None.
624
- Works in-place.
625
- """
626
- self.check(sample, condition_type, condition)
627
-
628
- if condition_type == 'audio':
629
- audio_cond = sample.audio[condition]
630
- depth = audio_cond.wav.shape[1]
631
- sample.audio[condition] = self.get_null_wav(audio_cond.wav, sr=audio_cond.sample_rate[0])
632
- else:
633
- if customized is None:
634
- if condition in ['type_info']:
635
- if "[Musicality-very-high]" in sample.text[condition]:
636
- sample.text[condition] = "[Musicality-very-low], ."
637
- print(f"cfg unconditioning: change sample.text[condition] to [Musicality-very-low]")
638
- else:
639
- sample.text[condition] = None
640
- else:
641
- sample.text[condition] = None
642
- else:
643
- text_cond = deepcopy(sample.text[condition])
644
- if "structure" in customized:
645
- for _s in ['[inst]', '[outro]', '[intro]', '[verse]', '[chorus]', '[bridge]']:
646
- text_cond = text_cond.replace(_s, "")
647
- text_cond = text_cond.replace(' , ', '')
648
- text_cond = text_cond.replace(" ", " ")
649
- if '.' in customized:
650
- text_cond = text_cond.replace(" . ", " ")
651
- text_cond = text_cond.replace(".", " ")
652
-
653
- sample.text[condition] = text_cond
654
-
655
- return sample
656
-
657
- def forward(self, samples: tp.List[ConditioningAttributes],
658
- condition_types=["wav", "text"],
659
- customized=None,
660
- ) -> tp.List[ConditioningAttributes]:
661
- """
662
- 100% dropout some condition attributes (description, prompt_wav) or types (text, wav) of
663
- samples during inference.
664
-
665
- Args:
666
- samples (list[ConditioningAttributes]): List of conditions.
667
- Returns:
668
- list[ConditioningAttributes]: List of conditions after all attributes were set to None.
669
- """
670
- new_samples = deepcopy(samples)
671
- for condition_type in condition_types:
672
- for sample in new_samples:
673
- for condition in sample.attributes[condition_type]:
674
- self.dropout_condition_customized(sample, condition_type, condition, customized)
675
- return new_samples
676
-
677
- class AttributeDropout(ClassifierFreeGuidanceDropout):
678
- """Dropout with a given probability per attribute.
679
- This is different from the behavior of ClassifierFreeGuidanceDropout as this allows for attributes
680
- to be dropped out separately. For example, "artist" can be dropped while "genre" remains.
681
- This is in contrast to ClassifierFreeGuidanceDropout where if "artist" is dropped "genre"
682
- must also be dropped.
683
-
684
- Args:
685
- p (tp.Dict[str, float]): A dict mapping between attributes and dropout probability. For example:
686
- ...
687
- "genre": 0.1,
688
- "artist": 0.5,
689
- "audio": 0.25,
690
- ...
691
- active_on_eval (bool, optional): Whether the dropout is active at eval. Default to False.
692
- seed (int, optional): Random seed.
693
- """
694
- def __init__(self, p: tp.Dict[str, tp.Dict[str, float]], active_on_eval: bool = False, seed: int = 1234):
695
- super().__init__(p=p, seed=seed)
696
- self.active_on_eval = active_on_eval
697
- # construct dict that return the values from p otherwise 0
698
- self.p = {}
699
- for condition_type, probs in p.items():
700
- self.p[condition_type] = defaultdict(lambda: 0, probs)
701
-
702
- def forward(self, samples: tp.List[ConditioningAttributes]) -> tp.List[ConditioningAttributes]:
703
- """
704
- Args:
705
- samples (list[ConditioningAttributes]): List of conditions.
706
- Returns:
707
- list[ConditioningAttributes]: List of conditions after certain attributes were set to None.
708
- """
709
- if not self.training and not self.active_on_eval:
710
- return samples
711
-
712
- samples = deepcopy(samples)
713
- for condition_type, ps in self.p.items(): # for condition types [text, wav]
714
- for condition, p in ps.items(): # for attributes of each type (e.g., [artist, genre])
715
- if torch.rand(1, generator=self.rng).item() < p:
716
- for sample in samples:
717
- self.dropout_condition(sample, condition_type, condition)
718
- return samples
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/modules/pattern.py DELETED
@@ -1,351 +0,0 @@
1
- from collections import namedtuple
2
- from dataclasses import dataclass
3
- from functools import lru_cache
4
- import logging
5
- import typing as tp
6
-
7
- from abc import ABC, abstractmethod
8
- import torch
9
-
10
- LayoutCoord = namedtuple('LayoutCoord', ['t', 'q']) # (timestep, codebook index)
11
- PatternLayout = tp.List[tp.List[LayoutCoord]] # Sequence of coordinates
12
- logger = logging.getLogger(__name__)
13
-
14
-
15
- @dataclass
16
- class Pattern:
17
- """Base implementation of a pattern over a sequence with multiple codebooks.
18
-
19
- The codebook pattern consists in a layout, defining for each sequence step
20
- the list of coordinates of each codebook timestep in the resulting interleaved sequence.
21
- The first item of the pattern is always an empty list in order to properly insert a special token
22
- to start with. For convenience, we also keep track of ``code_depth`` the number of codebooks used for the pattern
23
- and ``timesteps`` the number of timesteps corresponding to the original sequence.
24
-
25
- The pattern provides convenient methods to build and revert interleaved sequences from it:
26
- ``build_pattern_sequence`` maps a given a dense input tensor of multi-codebook sequence from [B, K, T]
27
- to the interleaved sequence of shape [B, K, S] applying the pattern, with S being the batch size,
28
- K being the number of codebooks, T the number of original timesteps and S the number of sequence steps
29
- for the output sequence. The unfilled positions are replaced with a special token and the built sequence
30
- is returned along with a mask indicating valid tokens.
31
- ``revert_pattern_sequence`` maps back an interleaved sequence of shape [B, K, S] to the original alignment
32
- of codebooks across timesteps to an output tensor of shape [B, K, T], using again a special token and a mask
33
- to fill and specify invalid positions if needed.
34
- See the dedicated methods for more details.
35
- """
36
- # Pattern layout, for each sequence step, we have a list of coordinates
37
- # corresponding to the original codebook timestep and position.
38
- # The first list is always an empty list in order to properly insert
39
- # a special token to start with.
40
- layout: PatternLayout
41
- timesteps: int
42
- code_depth: int
43
-
44
- def __post_init__(self):
45
- assert len(self.layout) > 0
46
- assert self.layout[0] == []
47
- self._validate_layout()
48
- self._build_reverted_sequence_scatter_indexes = lru_cache(100)(self._build_reverted_sequence_scatter_indexes)
49
- self._build_pattern_sequence_scatter_indexes = lru_cache(100)(self._build_pattern_sequence_scatter_indexes)
50
- logger.info("New pattern, time steps: %d, sequence steps: %d", self.timesteps, len(self.layout))
51
-
52
- def _validate_layout(self):
53
- """Runs checks on the layout to ensure a valid pattern is defined.
54
- A pattern is considered invalid if:
55
- - Multiple timesteps for a same codebook are defined in the same sequence step
56
- - The timesteps for a given codebook are not in ascending order as we advance in the sequence
57
- (this would mean that we have future timesteps before past timesteps).
58
- """
59
- q_timesteps = {q: 0 for q in range(self.code_depth)}
60
- for s, seq_coords in enumerate(self.layout):
61
- if len(seq_coords) > 0:
62
- qs = set()
63
- for coord in seq_coords:
64
- qs.add(coord.q)
65
- last_q_timestep = q_timesteps[coord.q]
66
- # assert coord.t >= last_q_timestep, \
67
- # f"Past timesteps are found in the sequence for codebook = {coord.q} at step {s}"
68
- q_timesteps[coord.q] = coord.t
69
- # each sequence step contains at max 1 coordinate per codebook
70
- assert len(qs) == len(seq_coords), \
71
- f"Multiple entries for a same codebook are found at step {s}"
72
-
73
- @property
74
- def num_sequence_steps(self):
75
- return len(self.layout) - 1
76
-
77
- @property
78
- def max_delay(self):
79
- max_t_in_seq_coords = 0
80
- for seq_coords in self.layout[1:]:
81
- for coords in seq_coords:
82
- max_t_in_seq_coords = max(max_t_in_seq_coords, coords.t + 1)
83
- return max_t_in_seq_coords - self.timesteps
84
-
85
- @property
86
- def valid_layout(self):
87
- valid_step = len(self.layout) - self.max_delay
88
- return self.layout[:valid_step]
89
-
90
- def get_sequence_coords_with_timestep(self, t: int, q: tp.Optional[int] = None):
91
- """Get codebook coordinates in the layout that corresponds to the specified timestep t
92
- and optionally to the codebook q. Coordinates are returned as a tuple with the sequence step
93
- and the actual codebook coordinates.
94
- """
95
- assert t <= self.timesteps, "provided timesteps is greater than the pattern's number of timesteps"
96
- if q is not None:
97
- assert q <= self.code_depth, "provided number of codebooks is greater than the pattern's number of codebooks"
98
- coords = []
99
- for s, seq_codes in enumerate(self.layout):
100
- for code in seq_codes:
101
- if code.t == t and (q is None or code.q == q):
102
- coords.append((s, code))
103
- return coords
104
-
105
- def get_steps_with_timestep(self, t: int, q: tp.Optional[int] = None) -> tp.List[int]:
106
- return [step for step, coords in self.get_sequence_coords_with_timestep(t, q)]
107
-
108
- def get_first_step_with_timesteps(self, t: int, q: tp.Optional[int] = None) -> tp.Optional[int]:
109
- steps_with_timesteps = self.get_steps_with_timestep(t, q)
110
- return steps_with_timesteps[0] if len(steps_with_timesteps) > 0 else None
111
-
112
- def _build_pattern_sequence_scatter_indexes(self, timesteps: int,
113
- code_depth: int,
114
- keep_only_valid_steps: bool,
115
- device: tp.Union[torch.device, str] = 'cpu'):
116
- """Build scatter indexes corresponding to the pattern, up to the provided sequence_steps.
117
-
118
- Args:
119
- timesteps (int): Maximum number of timesteps steps to consider.
120
- keep_only_valid_steps (bool): Restrict the pattern layout to match only valid steps.
121
- device (torch.device or str): Device for created tensors.
122
- Returns:
123
- indexes (torch.Tensor): Indexes corresponding to the sequence, of shape [K, S].
124
- mask (torch.Tensor): Mask corresponding to indexes that matches valid indexes, of shape [K, S].
125
- """
126
- assert code_depth == self.code_depth, f"invalid number of codebooks for the sequence and the pattern: {code_depth} != {self.code_depth}"
127
- assert timesteps <= self.timesteps, "invalid number of timesteps used to build the sequence from the pattern"
128
- # use the proper layout based on whether we limit ourselves to valid steps only or not,
129
- # note that using the valid_layout will result in a truncated sequence up to the valid steps
130
- ref_layout = self.valid_layout if keep_only_valid_steps else self.layout
131
- # single item indexing being super slow with pytorch vs. numpy, so we use numpy here
132
- indexes = torch.zeros(code_depth, len(ref_layout), dtype=torch.long).numpy()
133
- mask = torch.zeros(code_depth, len(ref_layout), dtype=torch.bool).numpy()
134
- # fill indexes with last sequence step value that will correspond to our special token
135
- # the last value is code_depth * timesteps as we have flattened z and append special token as the last token
136
- # which will correspond to the index: code_depth * timesteps
137
- indexes[:] = code_depth * timesteps
138
- # iterate over the pattern and fill scattered indexes and mask
139
- for s, sequence_coords in enumerate(ref_layout):
140
- for coords in sequence_coords:
141
- if coords.t < timesteps:
142
- indexes[coords.q, s] = coords.t + coords.q * timesteps
143
- mask[coords.q, s] = 1
144
- indexes = torch.from_numpy(indexes).to(device)
145
- mask = torch.from_numpy(mask).to(device)
146
- return indexes, mask
147
-
148
- def build_pattern_sequence(self, z: torch.Tensor, special_token: int, keep_only_valid_steps: bool = False):
149
- """Build sequence corresponding to the pattern from the input tensor z.
150
- The sequence is built using up to sequence_steps if specified, and non-pattern
151
- coordinates are filled with the special token.
152
-
153
- Args:
154
- z (torch.Tensor): Input tensor of multi-codebooks sequence, of shape [B, K, T].
155
- special_token (int): Special token used to fill non-pattern coordinates in the new sequence.
156
- keep_only_valid_steps (bool): Build a sequence from the pattern up to valid (= fully defined) steps.
157
- Steps that are beyond valid steps will be replaced by the special_token in that case.
158
- Returns:
159
- values (torch.Tensor): Interleaved sequence matching the pattern, of shape [B, K, S] with S
160
- corresponding either to the sequence_steps if provided, otherwise to the length of the pattern.
161
- indexes (torch.Tensor): Indexes corresponding to the interleaved sequence, of shape [K, S].
162
- mask (torch.Tensor): Mask corresponding to indexes that matches valid indexes of shape [K, S].
163
- """
164
- B, K, T = z.shape
165
- indexes, mask = self._build_pattern_sequence_scatter_indexes(
166
- T, K, keep_only_valid_steps=keep_only_valid_steps, device=str(z.device)
167
- )
168
- z = z.reshape(B, -1)
169
- # we append the special token as the last index of our flattened z tensor
170
- z = torch.cat([z, torch.zeros_like(z[:, :1]) + special_token], dim=1)
171
- values = z[:, indexes.view(-1)]
172
- values = values.view(B, K, indexes.shape[-1])
173
- # import pdb; pdb.set_trace()
174
- return values, indexes, mask
175
-
176
- def _build_reverted_sequence_scatter_indexes(self, sequence_steps: int, code_depth: int,
177
- keep_only_valid_steps: bool = False,
178
- is_model_output: bool = False,
179
- device: tp.Union[torch.device, str] = 'cpu'):
180
- """Builds scatter indexes required to retrieve the original multi-codebook sequence
181
- from interleaving pattern.
182
-
183
- Args:
184
- sequence_steps (int): Sequence steps.
185
- code_depth (int): Number of codebooks.
186
- keep_only_valid_steps (bool): Build a sequence from the pattern up to valid (= fully defined) steps.
187
- Steps that are beyond valid steps will be replaced by the special_token in that case.
188
- is_model_output (bool): Whether to keep the sequence item corresponding to initial special token or not.
189
- device (torch.device or str): Device for created tensors.
190
- Returns:
191
- indexes (torch.Tensor): Indexes for reconstructing the output, of shape [K, T].
192
- mask (torch.Tensor): Mask corresponding to indexes that matches valid indexes of shape [K, T].
193
- """
194
- ref_layout = self.valid_layout if keep_only_valid_steps else self.layout
195
- timesteps = self.timesteps
196
- assert code_depth == self.code_depth, f"invalid number of codebooks for the sequence and the pattern: {code_depth} != {self.code_depth}"
197
- assert sequence_steps <= len(ref_layout), \
198
- f"sequence to revert is longer than the defined pattern: {sequence_steps} > {len(ref_layout)}"
199
-
200
- # ensure we take the appropriate indexes to keep the model output from the first special token as well
201
- if is_model_output:
202
- ref_layout = ref_layout[1:]
203
-
204
- # single item indexing being super slow with pytorch vs. numpy, so we use numpy here
205
- indexes = torch.zeros(code_depth, timesteps, dtype=torch.long).numpy()
206
- mask = torch.zeros(code_depth, timesteps, dtype=torch.bool).numpy()
207
- # fill indexes with last sequence step value that will correspond to our special token
208
- indexes[:] = code_depth * sequence_steps
209
- for s, sequence_codes in enumerate(ref_layout):
210
- if s < sequence_steps:
211
- for code in sequence_codes:
212
- if code.t < timesteps:
213
- indexes[code.q, code.t] = s + code.q * sequence_steps
214
- mask[code.q, code.t] = 1
215
- indexes = torch.from_numpy(indexes).to(device)
216
- mask = torch.from_numpy(mask).to(device)
217
- return indexes, mask
218
-
219
- def revert_pattern_sequence(self, s: torch.Tensor, special_token: int, keep_only_valid_steps: bool = False):
220
- """Revert a sequence built from the pattern back to the original multi-codebook sequence without interleaving.
221
- The sequence is reverted using up to timesteps if specified, and non-pattern coordinates
222
- are filled with the special token.
223
-
224
- Args:
225
- s (torch.Tensor): Interleaved sequence tensor obtained from the pattern, of shape [B, K, S].
226
- special_token (int or float): Special token used to fill non-pattern coordinates in the new sequence.
227
- Returns:
228
- values (torch.Tensor): Interleaved sequence matching the pattern, of shape [B, K, T] with T
229
- corresponding either to the timesteps if provided, or the total timesteps in pattern otherwise.
230
- indexes (torch.Tensor): Indexes corresponding to the interleaved sequence, of shape [K, T].
231
- mask (torch.Tensor): Mask corresponding to indexes that matches valid indexes of shape [K, T].
232
- """
233
- B, K, S = s.shape
234
- indexes, mask = self._build_reverted_sequence_scatter_indexes(
235
- S, K, keep_only_valid_steps, is_model_output=False, device=str(s.device)
236
- )
237
- s = s.view(B, -1)
238
- # we append the special token as the last index of our flattened z tensor
239
- s = torch.cat([s, torch.zeros_like(s[:, :1]) + special_token], dim=1)
240
- values = s[:, indexes.view(-1)]
241
- values = values.view(B, K, indexes.shape[-1])
242
- return values, indexes, mask
243
-
244
- def revert_pattern_logits(self, logits: torch.Tensor, special_token: float, keep_only_valid_steps: bool = False):
245
- """Revert model logits obtained on a sequence built from the pattern
246
- back to a tensor matching the original sequence.
247
-
248
- This method is similar to ``revert_pattern_sequence`` with the following specificities:
249
- 1. It is designed to work with the extra cardinality dimension
250
- 2. We return the logits for the first sequence item that matches the special_token and
251
- which matching target in the original sequence is the first item of the sequence,
252
- while we skip the last logits as there is no matching target
253
- """
254
- B, card, K, S = logits.shape
255
- indexes, mask = self._build_reverted_sequence_scatter_indexes(
256
- S, K, keep_only_valid_steps, is_model_output=True, device=logits.device
257
- )
258
- logits = logits.reshape(B, card, -1)
259
- # we append the special token as the last index of our flattened z tensor
260
- logits = torch.cat([logits, torch.zeros_like(logits[:, :, :1]) + special_token], dim=-1) # [B, card, K x S]
261
- values = logits[:, :, indexes.view(-1)]
262
-
263
- values = values.view(B, card, K, indexes.shape[-1])
264
- return values, indexes, mask
265
-
266
-
267
-
268
- class CodebooksPatternProvider(ABC):
269
- """Abstraction around providing pattern for interleaving codebooks.
270
-
271
- The CodebooksPatternProvider abstraction allows to implement various strategies to
272
- define interleaving pattern of sequences composed of multiple codebooks. For a given
273
- number of codebooks `code_depth`, the pattern provider can generate a specified pattern
274
- corresponding to a sequence of `T` timesteps with `code_depth` parallel codebooks. This pattern
275
- can be used to construct a new sequence from the original codes respecting the specified
276
- pattern. The pattern is defined as a list of list of code coordinates, code coordinate
277
- being a tuple with the original timestep and codebook to build the new sequence.
278
- Note that all patterns must start with an empty list that is then used to insert a first
279
- sequence step of special tokens in the newly generated sequence.
280
-
281
- Args:
282
- code_depth (int): number of codebooks.
283
- cached (bool): if True, patterns for a given length are cached. In general
284
- that should be true for efficiency reason to avoid synchronization points.
285
- """
286
- def __init__(self, code_depth: int, cached: bool = True):
287
- assert code_depth > 0
288
- self.code_depth = code_depth
289
- self.get_pattern = lru_cache(100)(self.get_pattern) # type: ignore
290
-
291
- @abstractmethod
292
- def get_pattern(self, timesteps: int) -> Pattern:
293
- """Builds pattern with specific interleaving between codebooks.
294
-
295
- Args:
296
- timesteps (int): Total number of timesteps.
297
- """
298
- raise NotImplementedError()
299
-
300
-
301
- class DelayedPatternProvider(CodebooksPatternProvider):
302
- """Provider for delayed pattern across delayed codebooks.
303
- Codebooks are delayed in the sequence and sequence steps will contain codebooks
304
- from different timesteps.
305
-
306
- Example:
307
- Taking timesteps=4 and code_depth=3, delays=None, the multi-codebook sequence:
308
- [[1, 2, 3, 4],
309
- [1, 2, 3, 4],
310
- [1, 2, 3, 4]]
311
- The resulting sequence obtained from the returned pattern is:
312
- [[S, 1, 2, 3, 4],
313
- [S, S, 1, 2, 3],
314
- [S, S, S, 1, 2]]
315
- (with S being a special token)
316
-
317
- Args:
318
- code_depth (int): Number of codebooks.
319
- delays (list of int, optional): Delay for each of the codebooks.
320
- If delays not defined, each codebook is delayed by 1 compared to the previous one.
321
- flatten_first (int): Flatten the first N timesteps.
322
- empty_initial (int): Prepend with N empty list of coordinates.
323
- """
324
- def __init__(self, code_depth: int, delays: tp.Optional[tp.List[int]] = None,
325
- flatten_first: int = 0, empty_initial: int = 0):
326
- super().__init__(code_depth)
327
- if delays is None:
328
- delays = list(range(code_depth))
329
- self.delays = delays
330
- self.flatten_first = flatten_first
331
- self.empty_initial = empty_initial
332
- assert len(self.delays) == self.code_depth
333
- assert sorted(self.delays) == self.delays
334
-
335
- def get_pattern(self, timesteps: int) -> Pattern:
336
- out: PatternLayout = [[]]
337
- max_delay = max(self.delays)
338
- if self.empty_initial:
339
- out += [[] for _ in range(self.empty_initial)]
340
- if self.flatten_first:
341
- for t in range(min(timesteps, self.flatten_first)):
342
- for q in range(self.code_depth):
343
- out.append([LayoutCoord(t, q)])
344
- for t in range(self.flatten_first, timesteps + max_delay):
345
- v = []
346
- for q, delay in enumerate(self.delays):
347
- t_for_q = t - delay
348
- if t_for_q >= self.flatten_first:
349
- v.append(LayoutCoord(t_for_q, q))
350
- out.append(v)
351
- return Pattern(out, code_depth=self.code_depth, timesteps=timesteps)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/modules/streaming.py DELETED
@@ -1,112 +0,0 @@
1
- """
2
- Streaming module API that should be implemented by all Streaming components,
3
- """
4
-
5
- from contextlib import contextmanager
6
- import typing as tp
7
- from torch import nn
8
- import torch
9
-
10
-
11
- State = tp.Dict[str, torch.Tensor]
12
-
13
- class StreamingModule(nn.Module):
14
- """Common API for streaming components.
15
-
16
- Each streaming component has a streaming state, which is just a dict[str, Tensor].
17
- By convention, the first dim of each tensor must be the batch size.
18
- Don't use dots in the key names, as this would clash with submodules
19
- (like in state_dict).
20
-
21
- If `self._is_streaming` is True, the component should use and remember
22
- the proper state inside `self._streaming_state`.
23
-
24
- To set a streaming component in streaming state, use
25
-
26
- with module.streaming():
27
- ...
28
-
29
- This will automatically reset the streaming state when exiting the context manager.
30
- This also automatically propagates to all streaming children module.
31
-
32
- Some module might also implement the `StreamingModule.flush` method, although
33
- this one is trickier, as all parents module must be StreamingModule and implement
34
- it as well for it to work properly. See `StreamingSequential` after.
35
- """
36
- def __init__(self) -> None:
37
- super().__init__()
38
- self._streaming_state: State = {}
39
- self._is_streaming = False
40
-
41
- def _apply_named_streaming(self, fn: tp.Any):
42
- for name, module in self.named_modules():
43
- if isinstance(module, StreamingModule):
44
- fn(name, module)
45
-
46
- def _set_streaming(self, streaming: bool):
47
- def _set_streaming(name, module):
48
- module._is_streaming = streaming
49
- self._apply_named_streaming(_set_streaming)
50
-
51
- @contextmanager
52
- def streaming(self):
53
- """Context manager to enter streaming mode. Reset streaming state on exit."""
54
- self._set_streaming(True)
55
- try:
56
- yield
57
- finally:
58
- self._set_streaming(False)
59
- self.reset_streaming()
60
-
61
- def reset_streaming(self):
62
- """Reset the streaming state."""
63
- def _reset(name: str, module: StreamingModule):
64
- module._streaming_state.clear()
65
-
66
- self._apply_named_streaming(_reset)
67
-
68
- def get_streaming_state(self) -> State:
69
- """Return the streaming state, including that of sub-modules."""
70
- state: State = {}
71
-
72
- def _add(name: str, module: StreamingModule):
73
- if name:
74
- name += "."
75
- for key, value in module._streaming_state.items():
76
- state[name + key] = value
77
-
78
- self._apply_named_streaming(_add)
79
- return state
80
-
81
- def set_streaming_state(self, state: State):
82
- """Set the streaming state, including that of sub-modules."""
83
- state = dict(state)
84
-
85
- def _set(name: str, module: StreamingModule):
86
- if name:
87
- name += "."
88
- module._streaming_state.clear()
89
- for key, value in list(state.items()):
90
- # complexity is not ideal here, but probably fine.
91
- if key.startswith(name):
92
- local_key = key[len(name):]
93
- if '.' not in local_key:
94
- module._streaming_state[local_key] = value
95
- del state[key]
96
-
97
- self._apply_named_streaming(_set)
98
- assert len(state) == 0, list(state.keys())
99
-
100
- def flush(self, x: tp.Optional[torch.Tensor] = None):
101
- """Flush any remaining outputs that were waiting for completion.
102
- Typically, for convolutions, this will add the final padding
103
- and process the last buffer.
104
-
105
- This should take an optional argument `x`, which will be provided
106
- if a module before this one in the streaming pipeline has already
107
- spitted out a flushed out buffer.
108
- """
109
- if x is None:
110
- return None
111
- else:
112
- return self(x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/audio.py DELETED
@@ -1,304 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- """
4
- @File : audio.py
5
- @Time : 2023/8/8 下午7:18
6
- @Author : waytan
7
- @Contact : waytan@tencent.com
8
- @License : (C)Copyright 2023, Tencent
9
- @Desc : Audio
10
- """
11
- import json
12
- import subprocess as sp
13
- import typing as tp
14
- from pathlib import Path
15
-
16
- import lameenc
17
- import julius
18
- import torch
19
- import numpy as np
20
- import torchaudio as ta
21
- from contextlib import contextmanager
22
- import tempfile
23
- import os
24
-
25
- @contextmanager
26
- def temp_filenames(count: int, delete=True):
27
- names = []
28
- try:
29
- for _ in range(count):
30
- names.append(tempfile.NamedTemporaryFile(delete=False).name)
31
- yield names
32
- finally:
33
- if delete:
34
- for name in names:
35
- os.unlink(name)
36
-
37
-
38
- def _read_info(path):
39
- stdout_data = sp.check_output([
40
- 'ffprobe', "-loglevel", "panic",
41
- str(path), '-print_format', 'json', '-show_format', '-show_streams'
42
- ])
43
- return json.loads(stdout_data.decode('utf-8'))
44
-
45
-
46
- class AudioFile:
47
- """
48
- Allows to read audio from any format supported by ffmpeg, as well as resampling or
49
- converting to mono on the fly. See :method:`read` for more details.
50
- """
51
- def __init__(self, path: Path):
52
- self.path = Path(path)
53
- self._info = None
54
-
55
- def __repr__(self):
56
- features = [("path", self.path)]
57
- features.append(("samplerate", self.samplerate()))
58
- features.append(("channels", self.channels()))
59
- features.append(("streams", len(self)))
60
- features_str = ", ".join(f"{name}={value}" for name, value in features)
61
- return f"AudioFile({features_str})"
62
-
63
- @property
64
- def info(self):
65
- if self._info is None:
66
- self._info = _read_info(self.path)
67
- return self._info
68
-
69
- @property
70
- def duration(self):
71
- return float(self.info['format']['duration'])
72
-
73
- @property
74
- def _audio_streams(self):
75
- return [
76
- index for index, stream in enumerate(self.info["streams"])
77
- if stream["codec_type"] == "audio"
78
- ]
79
-
80
- def __len__(self):
81
- return len(self._audio_streams)
82
-
83
- def channels(self, stream=0):
84
- return int(self.info['streams'][self._audio_streams[stream]]['channels'])
85
-
86
- def samplerate(self, stream=0):
87
- return int(self.info['streams'][self._audio_streams[stream]]['sample_rate'])
88
-
89
- def read(self,
90
- seek_time=None,
91
- duration=None,
92
- streams=slice(None),
93
- samplerate=None,
94
- channels=None):
95
- """
96
- Slightly more efficient implementation than stempeg,
97
- in particular, this will extract all stems at once
98
- rather than having to loop over one file multiple times
99
- for each stream.
100
-
101
- Args:
102
- seek_time (float): seek time in seconds or None if no seeking is needed.
103
- duration (float): duration in seconds to extract or None to extract until the end.
104
- streams (slice, int or list): streams to extract, can be a single int, a list or
105
- a slice. If it is a slice or list, the output will be of size [S, C, T]
106
- with S the number of streams, C the number of channels and T the number of samples.
107
- If it is an int, the output will be [C, T].
108
- samplerate (int): if provided, will resample on the fly. If None, no resampling will
109
- be done. Original sampling rate can be obtained with :method:`samplerate`.
110
- channels (int): if 1, will convert to mono. We do not rely on ffmpeg for that
111
- as ffmpeg automatically scale by +3dB to conserve volume when playing on speakers.
112
- See https://sound.stackexchange.com/a/42710.
113
- Our definition of mono is simply the average of the two channels. Any other
114
- value will be ignored.
115
- """
116
- streams = np.array(range(len(self)))[streams]
117
- single = not isinstance(streams, np.ndarray)
118
- if single:
119
- streams = [streams]
120
-
121
- if duration is None:
122
- target_size = None
123
- query_duration = None
124
- else:
125
- target_size = int((samplerate or self.samplerate()) * duration)
126
- query_duration = float((target_size + 1) / (samplerate or self.samplerate()))
127
-
128
- with temp_filenames(len(streams)) as filenames:
129
- command = ['ffmpeg', '-y']
130
- command += ['-loglevel', 'panic']
131
- if seek_time:
132
- command += ['-ss', str(seek_time)]
133
- command += ['-i', str(self.path)]
134
- for stream, filename in zip(streams, filenames):
135
- command += ['-map', f'0:{self._audio_streams[stream]}']
136
- if query_duration is not None:
137
- command += ['-t', str(query_duration)]
138
- command += ['-threads', '1']
139
- command += ['-f', 'f32le']
140
- if samplerate is not None:
141
- command += ['-ar', str(samplerate)]
142
- command += [filename]
143
-
144
- sp.run(command, check=True)
145
- wavs = []
146
- for filename in filenames:
147
- wav = np.fromfile(filename, dtype=np.float32)
148
- wav = torch.from_numpy(wav)
149
- wav = wav.view(-1, self.channels()).t()
150
- if channels is not None:
151
- wav = convert_audio_channels(wav, channels)
152
- if target_size is not None:
153
- wav = wav[..., :target_size]
154
- wavs.append(wav)
155
- wav = torch.stack(wavs, dim=0)
156
- if single:
157
- wav = wav[0]
158
- return wav
159
-
160
-
161
- def convert_audio_channels(wav, channels=2):
162
- """Convert audio to the given number of channels."""
163
- *shape, src_channels, length = wav.shape
164
- if src_channels == channels:
165
- pass
166
- elif channels == 1:
167
- # Case 1:
168
- # The caller asked 1-channel audio, but the stream have multiple
169
- # channels, downmix all channels.
170
- wav = wav.mean(dim=-2, keepdim=True)
171
- elif src_channels == 1:
172
- # Case 2:
173
- # The caller asked for multiple channels, but the input file have
174
- # one single channel, replicate the audio over all channels.
175
- wav = wav.expand(*shape, channels, length)
176
- elif src_channels >= channels:
177
- # Case 3:
178
- # The caller asked for multiple channels, and the input file have
179
- # more channels than requested. In that case return the first channels.
180
- wav = wav[..., :channels, :]
181
- else:
182
- # Case 4: What is a reasonable choice here?
183
- raise ValueError('The audio file has less channels than requested but is not mono.')
184
- return wav
185
-
186
-
187
- def convert_audio(wav, from_samplerate, to_samplerate, channels):
188
- """Convert audio from a given samplerate to a target one and target number of channels."""
189
- wav = convert_audio_channels(wav, channels)
190
- return julius.resample_frac(wav, from_samplerate, to_samplerate)
191
-
192
-
193
- def i16_pcm(wav):
194
- """Convert audio to 16 bits integer PCM format."""
195
- if wav.dtype.is_floating_point:
196
- return (wav.clamp_(-1, 1) * (2**15 - 1)).short()
197
- else:
198
- return wav
199
-
200
-
201
- def f32_pcm(wav):
202
- """Convert audio to float 32 bits PCM format."""
203
- if wav.dtype.is_floating_point:
204
- return wav
205
- else:
206
- return wav.float() / (2**15 - 1)
207
-
208
-
209
- def as_dtype_pcm(wav):
210
- """Convert audio to either f32 pcm or i16 pcm depending on the given dtype."""
211
- if wav.dtype.is_floating_point:
212
- return f32_pcm(wav)
213
- else:
214
- return i16_pcm(wav)
215
-
216
-
217
- def encode_mp3(wav, path, samplerate=44100, bitrate=320, verbose=False):
218
- """Save given audio as mp3. This should work on all OSes."""
219
- c, _ = wav.shape
220
- wav = i16_pcm(wav)
221
- encoder = lameenc.Encoder()
222
- encoder.set_bit_rate(bitrate)
223
- encoder.set_in_sample_rate(samplerate)
224
- encoder.set_channels(c)
225
- encoder.set_quality(2) # 2-highest, 7-fastest
226
- if not verbose:
227
- encoder.silence()
228
- wav = wav.data.cpu()
229
- wav = wav.transpose(0, 1).numpy()
230
- mp3_data = encoder.encode(wav.tobytes())
231
- mp3_data += encoder.flush()
232
- with open(path, "wb") as f:
233
- f.write(mp3_data)
234
-
235
-
236
- def prevent_clip(wav, mode='rescale'):
237
- """
238
- different strategies for avoiding raw clipping.
239
- """
240
- if mode is None or mode == 'none':
241
- return wav
242
- assert wav.dtype.is_floating_point, "too late for clipping"
243
- if mode == 'rescale':
244
- wav = wav / max(1.01 * wav.abs().max(), 1)
245
- elif mode == 'clamp':
246
- wav = wav.clamp(-0.99, 0.99)
247
- elif mode == 'tanh':
248
- wav = torch.tanh(wav)
249
- else:
250
- raise ValueError(f"Invalid mode {mode}")
251
- return wav
252
-
253
-
254
- def save_audio(wav: torch.Tensor,
255
- path: tp.Union[str, Path],
256
- samplerate: int,
257
- bitrate: int = 320,
258
- clip: tp.Union[str] = 'rescale',
259
- bits_per_sample: tp.Union[int] = 16,
260
- as_float: bool = False):
261
- """Save audio file, automatically preventing clipping if necessary
262
- based on the given `clip` strategy. If the path ends in `.mp3`, this
263
- will save as mp3 with the given `bitrate`.
264
- """
265
- wav = prevent_clip(wav, mode=clip)
266
- path = Path(path)
267
- suffix = path.suffix.lower()
268
- if suffix == ".mp3":
269
- encode_mp3(wav, path, samplerate, bitrate, verbose=True)
270
- elif suffix == ".wav":
271
- if as_float:
272
- bits_per_sample = 32
273
- encoding = 'PCM_F'
274
- else:
275
- encoding = 'PCM_S'
276
- ta.save(str(path), wav, sample_rate=samplerate,
277
- encoding=encoding, bits_per_sample=bits_per_sample)
278
- elif suffix == ".flac":
279
- ta.save(str(path), wav, sample_rate=samplerate, bits_per_sample=bits_per_sample)
280
- else:
281
- raise ValueError(f"Invalid suffix for path: {suffix}")
282
-
283
-
284
- def load_track(track, audio_channels, samplerate):
285
- errors = {}
286
- wav = None
287
-
288
- try:
289
- wav = AudioFile(track).read(
290
- streams=0,
291
- samplerate=samplerate,
292
- channels=audio_channels)
293
- except sp.CalledProcessError:
294
- errors['ffmpeg'] = 'FFmpeg could not read the file.'
295
-
296
- if wav is None:
297
- try:
298
- wav, sr = ta.load(str(track))
299
- except RuntimeError as err:
300
- errors['torchaudio'] = err.args[0]
301
- else:
302
- wav = convert_audio(wav, sr, samplerate, audio_channels)
303
-
304
- return wav, errors
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/configs/models/transformer2D_wocross_inch112_1x4_multi_large.json DELETED
@@ -1,26 +0,0 @@
1
- {
2
- "_class_name": "Transformer2DModel",
3
- "_diffusers_version": "0.22.0.dev0",
4
- "activation_fn": "gelu-approximate",
5
- "attention_bias": true,
6
- "attention_head_dim": 72,
7
- "attention_type": "default",
8
- "cross_attention_dim": null,
9
- "double_self_attention": false,
10
- "dropout": 0.0,
11
- "in_channels": 96,
12
- "norm_elementwise_affine": false,
13
- "norm_eps": 1e-06,
14
- "norm_num_groups": 32,
15
- "norm_type": "ada_norm_single",
16
- "num_attention_heads": 22,
17
- "num_embeds_ada_norm": 1000,
18
- "num_layers": 24,
19
- "num_vector_embeds": null,
20
- "only_cross_attention": false,
21
- "out_channels": 32,
22
- "patch_size": 2,
23
- "sample_size": 384,
24
- "upcast_attention": false,
25
- "use_linear_projection": false
26
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/configs/scheduler/stable_diffusion_2.1_largenoise_sample.json DELETED
@@ -1,14 +0,0 @@
1
- {
2
- "_class_name": "DDIMScheduler",
3
- "_diffusers_version": "0.8.0",
4
- "beta_end": 0.02,
5
- "beta_schedule": "scaled_linear",
6
- "beta_start": 0.0015,
7
- "clip_sample": false,
8
- "num_train_timesteps": 1000,
9
- "prediction_type": "sample",
10
- "set_alpha_to_one": false,
11
- "skip_prk_steps": true,
12
- "steps_offset": 1,
13
- "trained_betas": null
14
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/generate_1rvq.py DELETED
@@ -1,228 +0,0 @@
1
- import torch
2
- import math
3
- import numpy as np
4
- from tqdm import tqdm
5
- from safetensors.torch import load_file
6
-
7
- from model_1rvq import PromptCondAudioDiffusion
8
- from tools.get_1dvae_large import get_model
9
-
10
- class Tango:
11
- def __init__(self, \
12
- model_path, \
13
- vae_config="",
14
- vae_model="",
15
- layer_num=6, \
16
- device="cuda:0"):
17
-
18
- self.sample_rate = 48000
19
- scheduler_name = "configs/scheduler/stable_diffusion_2.1_largenoise_sample.json"
20
- self.device = device
21
-
22
- self.vae = get_model(vae_config, vae_model)
23
- self.vae = self.vae.to(device)
24
- self.vae=self.vae.eval()
25
- self.layer_num = layer_num
26
-
27
- self.MAX_DURATION = 360
28
- main_config = {
29
- "num_channels":32,
30
- "unet_model_name":None,
31
- "unet_model_config_path":"configs/models/transformer2D_wocross_inch112_1x4_multi_large.json",
32
- "snr_gamma":None,
33
- }
34
- self.model = PromptCondAudioDiffusion(**main_config).to(device)
35
- if model_path.endswith(".safetensors"):
36
- main_weights = load_file(model_path)
37
- else:
38
- main_weights = torch.load(model_path, map_location=device)
39
- self.model.load_state_dict(main_weights, strict=False)
40
- print ("Successfully loaded checkpoint from:", model_path)
41
-
42
- self.model.eval()
43
- self.model.init_device_dtype(torch.device(device), torch.float32)
44
-
45
- # self.scheduler = DDIMScheduler.from_pretrained( \
46
- # scheduler_name, subfolder="scheduler")
47
- # self.scheduler = DDPMScheduler.from_pretrained( \
48
- # scheduler_name, subfolder="scheduler")
49
- # print("Successfully loaded inference scheduler from {}".format(scheduler_name))
50
-
51
- def sound2sound(self, orig_samples, lyric, st_et, batch_size=1, duration=40.96, steps=200, disable_progress=False,scenario = "start_seg"):
52
- """ Genrate audio without condition. """
53
- with torch.no_grad():
54
- if(orig_samples.shape[-1]<int(duration*48000)+480):
55
- orig_samples = torch.cat([orig_samples, torch.zeros(orig_samples.shape[0], int(duration*48000+480)-orig_samples.shape[-1], \
56
- dtype=orig_samples.dtype, device=orig_samples.device)], -1)
57
-
58
- orig_samples = orig_samples.to(self.device)
59
- saved_samples = orig_samples[:,0:40*48000].clamp(-1,1)
60
- orig_samples = orig_samples[:,0:40*48000].clamp(-1,1)
61
- max_volume = orig_samples.abs().max(dim=-1)[0]
62
- orig_samples = orig_samples/max_volume.unsqueeze(-1)
63
-
64
- latent_length = int((st_et[1] - st_et[0]) * 48000) // 1920 + 1
65
-
66
- true_latents = self.vae.encode_audio(orig_samples).permute(0,2,1)
67
-
68
- latents = self.model.inference(orig_samples.repeat(batch_size, 1), [lyric, ]*batch_size, true_latents, latent_length, additional_feats=[], guidance_scale=1.5, num_steps = steps, disable_progress=disable_progress,layer=6, scenario = scenario)
69
- latents = latents[:,:,:latent_length]
70
- audio = self.vae.decode_audio(latents)
71
- audio = torch.cat((audio, torch.zeros(audio.shape[0],audio.shape[1], 48000*40 - audio.shape[-1], dtype=audio.dtype, device=audio.device)), dim=-1)
72
-
73
- if(saved_samples.shape[-1]<audio.shape[-1]):
74
- saved_samples = torch.cat([saved_samples, torch.zeros(saved_samples.shape[0], audio.shape[-1]-saved_samples.shape[-1], dtype=saved_samples.dtype, device=saved_samples.device)],-1)
75
- else:
76
- saved_samples = saved_samples[:,0:audio.shape[-1]]
77
- output = torch.cat([saved_samples.detach().cpu(),audio[0].detach().cpu()],0)
78
- return output
79
-
80
- @torch.no_grad()
81
- @torch.autocast(device_type="cuda", dtype=torch.float32)
82
- def sound2code(self, orig_samples, batch_size=3):
83
- if(orig_samples.ndim == 2):
84
- audios = orig_samples.unsqueeze(0).to(self.device)
85
- elif(orig_samples.ndim == 3):
86
- audios = orig_samples.to(self.device)
87
- else:
88
- assert orig_samples.ndim in (2,3), orig_samples.shape
89
- audios = self.preprocess_audio(audios)
90
- audios = audios.squeeze(0)
91
- orig_length = audios.shape[-1]
92
- min_samples = int(40 * self.sample_rate)
93
- # 40秒对应10个token
94
- output_len = int(orig_length / float(self.sample_rate) * 25) + 1
95
-
96
- while(audios.shape[-1] < min_samples):
97
- audios = torch.cat([audios, audios], -1)
98
- int_max_len=audios.shape[-1]//min_samples+1
99
- audios = torch.cat([audios, audios], -1)
100
- audios=audios[:,:int(int_max_len*(min_samples))]
101
- codes_list=[]
102
-
103
- audio_input = audios.reshape(2, -1, min_samples).permute(1, 0, 2).reshape(-1, 2, min_samples)
104
-
105
- for audio_inx in range(0, audio_input.shape[0], batch_size):
106
- codes, _, spk_embeds = self.model.fetch_codes_batch((audio_input[audio_inx:audio_inx+batch_size]), additional_feats=[],layer=self.layer_num)
107
- codes_list.append(torch.cat(codes, 1))
108
-
109
- codes = torch.cat(codes_list, 0).permute(1,0,2).reshape(1, -1)[None] # B 3 T -> 3 B T
110
- codes=codes[:,:,:output_len]
111
-
112
- return codes
113
-
114
- @torch.no_grad()
115
- def code2sound(self, codes, prompt=None, duration=40, guidance_scale=1.5, num_steps=20, disable_progress=False, chunked=False, chunk_size=128):
116
- codes = codes.to(self.device)
117
-
118
- min_samples = int(duration * 25) # 40ms per frame
119
- hop_samples = min_samples // 4 * 3
120
- ovlp_samples = min_samples - hop_samples
121
- hop_frames = hop_samples
122
- ovlp_frames = ovlp_samples
123
- first_latent = torch.randn(codes.shape[0], min_samples, 64).to(self.device)
124
- first_latent_length = 0
125
- first_latent_codes_length = 0
126
-
127
- if(isinstance(prompt, torch.Tensor)):
128
- # prepare prompt
129
- prompt = prompt.to(self.device)
130
- if(prompt.ndim == 3):
131
- assert prompt.shape[0] == 1, prompt.shape
132
- prompt = prompt[0]
133
- elif(prompt.ndim == 1):
134
- prompt = prompt.unsqueeze(0).repeat(2,1)
135
- elif(prompt.ndim == 2):
136
- if(prompt.shape[0] == 1):
137
- prompt = prompt.repeat(2,1)
138
-
139
- if(prompt.shape[-1] < int(30 * self.sample_rate)):
140
- # if less than 30s, just choose the first 10s
141
- prompt = prompt[:,:int(10*self.sample_rate)] # limit max length to 10.24
142
- else:
143
- # else choose from 20.48s which might includes verse or chorus
144
- prompt = prompt[:,int(20*self.sample_rate):int(30*self.sample_rate)] # limit max length to 10.24
145
-
146
- true_latent = self.vae.encode_audio(prompt).permute(0,2,1)
147
- first_latent[:,0:true_latent.shape[1],:] = true_latent
148
- first_latent_length = true_latent.shape[1]
149
- first_latent_codes = self.sound2code(prompt)
150
- first_latent_codes_length = first_latent_codes.shape[-1]
151
- codes = torch.cat([first_latent_codes, codes], -1)
152
-
153
- codes_len= codes.shape[-1]
154
- target_len = int((codes_len - first_latent_codes_length) / 100 * 4 * self.sample_rate)
155
- # target_len = int(codes_len / 100 * 4 * self.sample_rate)
156
- # code repeat
157
- if(codes_len < min_samples):
158
- while(codes.shape[-1] < min_samples):
159
- codes = torch.cat([codes, codes], -1)
160
- codes = codes[:,:,0:min_samples]
161
- codes_len = codes.shape[-1]
162
- if((codes_len - ovlp_samples) % hop_samples > 0):
163
- len_codes=math.ceil((codes_len - ovlp_samples) / float(hop_samples)) * hop_samples + ovlp_samples
164
- while(codes.shape[-1] < len_codes):
165
- codes = torch.cat([codes, codes], -1)
166
- codes = codes[:,:,0:len_codes]
167
- latent_length = min_samples
168
- latent_list = []
169
- spk_embeds = torch.zeros([1, 32, 1, 32], device=codes.device)
170
- with torch.autocast(device_type="cuda", dtype=torch.float16):
171
- for sinx in tqdm(range(0, codes.shape[-1]-hop_samples, hop_samples), desc="Processed wav"):
172
- codes_input=[]
173
- codes_input.append(codes[:,:,sinx:sinx+min_samples])
174
- if(sinx == 0):
175
- incontext_length = first_latent_length
176
- latents = self.model.inference_codes(codes_input, spk_embeds, first_latent, latent_length, incontext_length=incontext_length, additional_feats=[], guidance_scale=1.5, num_steps = num_steps, disable_progress=disable_progress, scenario='other_seg')
177
- latent_list.append(latents)
178
- else:
179
- true_latent = latent_list[-1][:,:,-ovlp_frames:].permute(0,2,1)
180
- len_add_to_1000 = min_samples - true_latent.shape[-2]
181
- incontext_length = true_latent.shape[-2]
182
- true_latent = torch.cat([true_latent, torch.randn(true_latent.shape[0], len_add_to_1000, true_latent.shape[-1]).to(self.device)], -2)
183
- latents = self.model.inference_codes(codes_input, spk_embeds, true_latent, latent_length, incontext_length=incontext_length, additional_feats=[], guidance_scale=1.5, num_steps = num_steps, disable_progress=disable_progress, scenario='other_seg')
184
- latent_list.append(latents)
185
-
186
- latent_list = [l.float() for l in latent_list]
187
- latent_list[0] = latent_list[0][:,:,first_latent_length:]
188
- min_samples = int(min_samples * self.sample_rate // 1000 * 40)
189
- hop_samples = int(hop_samples * self.sample_rate // 1000 * 40)
190
- ovlp_samples = min_samples - hop_samples
191
- with torch.no_grad():
192
- output = None
193
- for i in range(len(latent_list)):
194
- latent = latent_list[i]
195
- cur_output = self.vae.decode_audio(latent, chunked=chunked, chunk_size=chunk_size)[0].detach().cpu()
196
-
197
- if output is None:
198
- output = cur_output
199
- else:
200
- ov_win = torch.from_numpy(np.linspace(0, 1, ovlp_samples)[None, :])
201
- ov_win = torch.cat([ov_win, 1 - ov_win], -1)
202
- output[:, -ovlp_samples:] = output[:, -ovlp_samples:] * ov_win[:, -ovlp_samples:] + cur_output[:, 0:ovlp_samples] * ov_win[:, 0:ovlp_samples]
203
- output = torch.cat([output, cur_output[:, ovlp_samples:]], -1)
204
- output = output[:, 0:target_len]
205
- return output
206
-
207
- @torch.no_grad()
208
- def preprocess_audio(self, input_audios, threshold=0.8):
209
- assert len(input_audios.shape) == 3, input_audios.shape
210
- nchan = input_audios.shape[1]
211
- input_audios = input_audios.reshape(input_audios.shape[0], -1)
212
- norm_value = torch.ones_like(input_audios[:,0])
213
- max_volume = input_audios.abs().max(dim=-1)[0]
214
- norm_value[max_volume>threshold] = max_volume[max_volume>threshold] / threshold
215
- return input_audios.reshape(input_audios.shape[0], nchan, -1)/norm_value.unsqueeze(-1).unsqueeze(-1)
216
-
217
- @torch.no_grad()
218
- def sound2sound(self, sound, prompt=None, steps=50, disable_progress=False):
219
- codes = self.sound2code(sound)
220
- wave = self.code2sound(codes, prompt, guidance_scale=1.5, num_steps=steps, disable_progress=disable_progress)
221
- return wave
222
-
223
- def to(self, device=None, dtype=None, non_blocking=False):
224
- if device is not None:
225
- self.device = device
226
- self.model.device = device
227
- self.model = self.model.to(device, dtype, non_blocking)
228
- return self
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/generate_septoken.py DELETED
@@ -1,309 +0,0 @@
1
- import json
2
- import torch
3
- from tqdm import tqdm
4
- from model_septoken import PromptCondAudioDiffusion
5
- import torchaudio
6
- import librosa
7
- import os
8
- import math
9
- import numpy as np
10
- # from tools.get_mulan import get_mulan
11
- from tools.get_1dvae_large import get_model
12
- import tools.torch_tools as torch_tools
13
- from safetensors.torch import load_file
14
- from third_party.demucs.models.pretrained import get_model_from_yaml
15
- from filelock import FileLock
16
-
17
-
18
- class Separator:
19
- def __init__(self, dm_model_path='demucs/ckpt/htdemucs.pth', dm_config_path='demucs/ckpt/htdemucs.yaml', gpu_id=0) -> None:
20
- if torch.cuda.is_available() and gpu_id < torch.cuda.device_count():
21
- self.device = torch.device(f"cuda:{gpu_id}")
22
- else:
23
- self.device = torch.device("cpu")
24
- self.demucs_model = self.init_demucs_model(dm_model_path, dm_config_path)
25
-
26
- def init_demucs_model(self, model_path, config_path):
27
- model = get_model_from_yaml(config_path, model_path)
28
- model.to(self.device)
29
- model.eval()
30
- return model
31
-
32
- def load_audio(self, f):
33
- a, fs = torchaudio.load(f)
34
- if (fs != 48000):
35
- a = torchaudio.functional.resample(a, fs, 48000)
36
- # if a.shape[-1] >= 48000*10:
37
- # a = a[..., :48000*10]
38
- # else:
39
- # a = torch.cat([a, a], -1)
40
- # return a[:, 0:48000*10]
41
- return a
42
-
43
- def run(self, audio_path, output_dir='demucs/test_output', ext=".flac"):
44
- name, _ = os.path.splitext(os.path.split(audio_path)[-1])
45
- output_paths = []
46
- # lock_path = os.path.join(output_dir, f"{name}.lock")
47
- # with FileLock(lock_path): # 加一个避免多卡访问时死锁
48
- for stem in self.demucs_model.sources:
49
- output_path = os.path.join(output_dir, f"{name}_{stem}{ext}")
50
- if os.path.exists(output_path):
51
- output_paths.append(output_path)
52
- if len(output_paths) == 1: # 4
53
- # drums_path, bass_path, other_path, vocal_path = output_paths
54
- vocal_path = output_paths[0]
55
- else:
56
- lock_path = os.path.join(output_dir, f"{name}_separate.lock")
57
- with FileLock(lock_path):
58
- drums_path, bass_path, other_path, vocal_path = self.demucs_model.separate(audio_path, output_dir, device=self.device)
59
- full_audio = self.load_audio(audio_path)
60
- vocal_audio = self.load_audio(vocal_path)
61
- minlen = min(full_audio.shape[-1], vocal_audio.shape[-1])
62
- # bgm_audio = full_audio[:, 0:minlen] - vocal_audio[:, 0:minlen]
63
- bgm_audio = self.load_audio(drums_path) + self.load_audio(bass_path) + self.load_audio(other_path)
64
- for path in [drums_path, bass_path, other_path, vocal_path]:
65
- os.remove(path)
66
- return full_audio, vocal_audio, bgm_audio
67
-
68
- class Tango:
69
- def __init__(self, \
70
- model_path, \
71
- vae_config,
72
- vae_model,
73
- layer_vocal=7,\
74
- layer_bgm=3,\
75
- device="cuda:0"):
76
-
77
- self.sample_rate = 48000
78
- scheduler_name = "configs/scheduler/stable_diffusion_2.1_largenoise_sample.json"
79
- self.device = device
80
-
81
- self.vae = get_model(vae_config, vae_model)
82
- self.vae = self.vae.to(device)
83
- self.vae=self.vae.eval()
84
- self.layer_vocal=layer_vocal
85
- self.layer_bgm=layer_bgm
86
-
87
- self.MAX_DURATION = 360
88
- main_config = {
89
- "num_channels":32,
90
- "unet_model_name":None,
91
- "unet_model_config_path":"configs/models/transformer2D_wocross_inch112_1x4_multi_large.json",
92
- "snr_gamma":None,
93
- }
94
- self.model = PromptCondAudioDiffusion(**main_config).to(device)
95
- if model_path.endswith(".safetensors"):
96
- main_weights = load_file(model_path)
97
- else:
98
- main_weights = torch.load(model_path, map_location=device)
99
- self.model.load_state_dict(main_weights, strict=False)
100
- print ("Successfully loaded checkpoint from:", model_path)
101
-
102
- self.model.eval()
103
- self.model.init_device_dtype(torch.device(device), torch.float32)
104
-
105
- # self.scheduler = DDIMScheduler.from_pretrained( \
106
- # scheduler_name, subfolder="scheduler")
107
- # self.scheduler = DDPMScheduler.from_pretrained( \
108
- # scheduler_name, subfolder="scheduler")
109
- print("Successfully loaded inference scheduler from {}".format(scheduler_name))
110
-
111
-
112
- @torch.no_grad()
113
- @torch.autocast(device_type="cuda", dtype=torch.float32)
114
- def sound2code(self, orig_vocal, orig_bgm, batch_size=8):
115
- if(orig_vocal.ndim == 2):
116
- audios_vocal = orig_vocal.unsqueeze(0).to(self.device)
117
- elif(orig_vocal.ndim == 3):
118
- audios_vocal = orig_vocal.to(self.device)
119
- else:
120
- assert orig_vocal.ndim in (2,3), orig_vocal.shape
121
-
122
- if(orig_bgm.ndim == 2):
123
- audios_bgm = orig_bgm.unsqueeze(0).to(self.device)
124
- elif(orig_bgm.ndim == 3):
125
- audios_bgm = orig_bgm.to(self.device)
126
- else:
127
- assert orig_bgm.ndim in (2,3), orig_bgm.shape
128
-
129
-
130
- audios_vocal = self.preprocess_audio(audios_vocal)
131
- audios_vocal = audios_vocal.squeeze(0)
132
- audios_bgm = self.preprocess_audio(audios_bgm)
133
- audios_bgm = audios_bgm.squeeze(0)
134
- if audios_vocal.shape[-1] > audios_bgm.shape[-1]:
135
- audios_vocal = audios_vocal[:,:audios_bgm.shape[-1]]
136
- else:
137
- audios_bgm = audios_bgm[:,:audios_vocal.shape[-1]]
138
-
139
-
140
- orig_length = audios_vocal.shape[-1]
141
- min_samples = int(40 * self.sample_rate)
142
- # 40秒对应10个token
143
- output_len = int(orig_length / float(self.sample_rate) * 25) + 1
144
-
145
- while(audios_vocal.shape[-1] < min_samples):
146
- audios_vocal = torch.cat([audios_vocal, audios_vocal], -1)
147
- audios_bgm = torch.cat([audios_bgm, audios_bgm], -1)
148
- int_max_len=audios_vocal.shape[-1]//min_samples+1
149
- audios_vocal = torch.cat([audios_vocal, audios_vocal], -1)
150
- audios_bgm = torch.cat([audios_bgm, audios_bgm], -1)
151
- audios_vocal=audios_vocal[:,:int(int_max_len*(min_samples))]
152
- audios_bgm=audios_bgm[:,:int(int_max_len*(min_samples))]
153
- codes_vocal_list=[]
154
- codes_bgm_list=[]
155
-
156
-
157
-
158
- audio_vocal_input = audios_vocal.reshape(2, -1, min_samples).permute(1, 0, 2).reshape(-1, 2, min_samples)
159
- audio_bgm_input = audios_bgm.reshape(2, -1, min_samples).permute(1, 0, 2).reshape(-1, 2, min_samples)
160
-
161
- for audio_inx in range(0, audio_vocal_input.shape[0], batch_size):
162
- [codes_vocal,codes_bgm], _, spk_embeds = self.model.fetch_codes_batch((audio_vocal_input[audio_inx:audio_inx+batch_size]), (audio_bgm_input[audio_inx:audio_inx+batch_size]), additional_feats=[],layer_vocal=self.layer_vocal,layer_bgm=self.layer_bgm)
163
- codes_vocal_list.append(codes_vocal)
164
- codes_bgm_list.append(codes_bgm)
165
-
166
- codes_vocal = torch.cat(codes_vocal_list, 0).permute(1,0,2).reshape(1, -1)[None]
167
- codes_bgm = torch.cat(codes_bgm_list, 0).permute(1,0,2).reshape(1, -1)[None]
168
- codes_vocal=codes_vocal[:,:,:output_len]
169
- codes_bgm=codes_bgm[:,:,:output_len]
170
-
171
- return codes_vocal, codes_bgm
172
-
173
- @torch.no_grad()
174
- def code2sound(self, codes, prompt_vocal=None, prompt_bgm=None, duration=40, guidance_scale=1.5, num_steps=20, disable_progress=False, chunked=False, chunk_size=128):
175
- codes_vocal,codes_bgm = codes
176
- codes_vocal = codes_vocal.to(self.device)
177
- codes_bgm = codes_bgm.to(self.device)
178
-
179
- min_samples = duration * 25 # 40ms per frame
180
- hop_samples = min_samples // 4 * 3
181
- ovlp_samples = min_samples - hop_samples
182
- hop_frames = hop_samples
183
- ovlp_frames = ovlp_samples
184
- first_latent = torch.randn(codes_vocal.shape[0], min_samples, 64).to(self.device)
185
- first_latent_length = 0
186
- first_latent_codes_length = 0
187
-
188
-
189
- if(isinstance(prompt_vocal, torch.Tensor) and isinstance(prompt_bgm, torch.Tensor)):
190
- # prepare prompt
191
- prompt_vocal = prompt_vocal.to(self.device)
192
- prompt_bgm = prompt_bgm.to(self.device)
193
- if(prompt_vocal.ndim == 3):
194
- assert prompt_vocal.shape[0] == 1, prompt_vocal.shape
195
- prompt_vocal = prompt_vocal[0]
196
- prompt_bgm = prompt_bgm[0]
197
- elif(prompt_vocal.ndim == 1):
198
- prompt_vocal = prompt_vocal.unsqueeze(0).repeat(2,1)
199
- prompt_bgm = prompt_bgm.unsqueeze(0).repeat(2,1)
200
- elif(prompt_vocal.ndim == 2):
201
- if(prompt_vocal.shape[0] == 1):
202
- prompt_vocal = prompt_vocal.repeat(2,1)
203
- prompt_bgm = prompt_bgm.repeat(2,1)
204
-
205
- if(prompt_vocal.shape[-1] < int(30 * self.sample_rate)):
206
- # if less than 30s, just choose the first 10s
207
- prompt_vocal = prompt_vocal[:,:int(10*self.sample_rate)] # limit max length to 10.24
208
- prompt_bgm = prompt_bgm[:,:int(10*self.sample_rate)] # limit max length to 10.24
209
- else:
210
- # else choose from 20.48s which might includes verse or chorus
211
- prompt_vocal = prompt_vocal[:,int(20*self.sample_rate):int(30*self.sample_rate)] # limit max length to 10.24
212
- prompt_bgm = prompt_bgm[:,int(20*self.sample_rate):int(30*self.sample_rate)] # limit max length to 10.24
213
-
214
- true_latent = self.vae.encode_audio(prompt_vocal+prompt_bgm).permute(0,2,1)
215
-
216
- first_latent[:,0:true_latent.shape[1],:] = true_latent
217
- first_latent_length = true_latent.shape[1]
218
- first_latent_codes = self.sound2code(prompt_vocal, prompt_bgm)
219
- first_latent_codes_vocal = first_latent_codes[0]
220
- first_latent_codes_bgm = first_latent_codes[1]
221
- first_latent_codes_length = first_latent_codes_vocal.shape[-1]
222
- codes_vocal = torch.cat([first_latent_codes_vocal, codes_vocal], -1)
223
- codes_bgm = torch.cat([first_latent_codes_bgm, codes_bgm], -1)
224
-
225
-
226
- codes_len= codes_vocal.shape[-1]
227
- target_len = int((codes_len - first_latent_codes_length) / 100 * 4 * self.sample_rate)
228
- # target_len = int(codes_len / 100 * 4 * self.sample_rate)
229
- # code repeat
230
- if(codes_len < min_samples):
231
- while(codes_vocal.shape[-1] < min_samples):
232
- codes_vocal = torch.cat([codes_vocal, codes_vocal], -1)
233
- codes_bgm = torch.cat([codes_bgm, codes_bgm], -1)
234
-
235
- codes_vocal = codes_vocal[:,:,0:min_samples]
236
- codes_bgm = codes_bgm[:,:,0:min_samples]
237
- codes_len = codes_vocal.shape[-1]
238
- if((codes_len - ovlp_samples) % hop_samples > 0):
239
- len_codes=math.ceil((codes_len - ovlp_samples) / float(hop_samples)) * hop_samples + ovlp_samples
240
- while(codes_vocal.shape[-1] < len_codes):
241
- codes_vocal = torch.cat([codes_vocal, codes_vocal], -1)
242
- codes_bgm = torch.cat([codes_bgm, codes_bgm], -1)
243
- codes_vocal = codes_vocal[:,:,0:len_codes]
244
- codes_bgm = codes_bgm[:,:,0:len_codes]
245
- latent_length = min_samples
246
- latent_list = []
247
- spk_embeds = torch.zeros([1, 32, 1, 32], device=codes_vocal.device)
248
- with torch.autocast(device_type="cuda", dtype=torch.float16):
249
- for sinx in tqdm(range(0, codes_vocal.shape[-1]-hop_samples, hop_samples), desc="Processed wav"):
250
- codes_vocal_input=codes_vocal[:,:,sinx:sinx+min_samples]
251
- codes_bgm_input=codes_bgm[:,:,sinx:sinx+min_samples]
252
- if(sinx == 0):
253
- incontext_length = first_latent_length
254
- latents = self.model.inference_codes([codes_vocal_input,codes_bgm_input], spk_embeds, first_latent, latent_length, incontext_length=incontext_length, additional_feats=[], guidance_scale=1.5, num_steps = num_steps, disable_progress=disable_progress, scenario='other_seg')
255
- latent_list.append(latents)
256
- else:
257
- true_latent = latent_list[-1][:,:,-ovlp_frames:].permute(0,2,1)
258
- len_add_to_1000 = min_samples - true_latent.shape[-2]
259
- incontext_length = true_latent.shape[-2]
260
- true_latent = torch.cat([true_latent, torch.randn(true_latent.shape[0], len_add_to_1000, true_latent.shape[-1]).to(self.device)], -2)
261
- latents = self.model.inference_codes([codes_vocal_input,codes_bgm_input], spk_embeds, true_latent, latent_length, incontext_length=incontext_length, additional_feats=[], guidance_scale=1.5, num_steps = num_steps, disable_progress=disable_progress, scenario='other_seg')
262
- latent_list.append(latents)
263
-
264
- latent_list = [l.float() for l in latent_list]
265
- latent_list[0] = latent_list[0][:,:,first_latent_length:]
266
- min_samples = int(min_samples * self.sample_rate // 1000 * 40)
267
- hop_samples = int(hop_samples * self.sample_rate // 1000 * 40)
268
- ovlp_samples = min_samples - hop_samples
269
- torch.cuda.empty_cache()
270
- with torch.no_grad():
271
- output = None
272
- for i in range(len(latent_list)):
273
- latent = latent_list[i]
274
- cur_output = self.vae.decode_audio(latent, chunked=chunked, chunk_size=chunk_size)[0].detach().cpu()
275
-
276
- if output is None:
277
- output = cur_output
278
- else:
279
- ov_win = torch.from_numpy(np.linspace(0, 1, ovlp_samples)[None, :])
280
- ov_win = torch.cat([ov_win, 1 - ov_win], -1)
281
- output[:, -ovlp_samples:] = output[:, -ovlp_samples:] * ov_win[:, -ovlp_samples:] + cur_output[:, 0:ovlp_samples] * ov_win[:, 0:ovlp_samples]
282
- output = torch.cat([output, cur_output[:, ovlp_samples:]], -1)
283
- output = output[:, 0:target_len]
284
- return output
285
-
286
- @torch.no_grad()
287
- def preprocess_audio(self, input_audios_vocal, threshold=0.8):
288
- assert len(input_audios_vocal.shape) == 3, input_audios_vocal.shape
289
- nchan = input_audios_vocal.shape[1]
290
- input_audios_vocal = input_audios_vocal.reshape(input_audios_vocal.shape[0], -1)
291
- norm_value = torch.ones_like(input_audios_vocal[:,0])
292
- max_volume = input_audios_vocal.abs().max(dim=-1)[0]
293
- norm_value[max_volume>threshold] = max_volume[max_volume>threshold] / threshold
294
- return input_audios_vocal.reshape(input_audios_vocal.shape[0], nchan, -1)/norm_value.unsqueeze(-1).unsqueeze(-1)
295
-
296
- @torch.no_grad()
297
- def sound2sound(self, orig_vocal,orig_bgm, prompt_vocal=None,prompt_bgm=None, steps=50, disable_progress=False):
298
- codes_vocal, codes_bgm = self.sound2code(orig_vocal,orig_bgm)
299
- codes=[codes_vocal, codes_bgm]
300
- wave = self.code2sound(codes, prompt_vocal,prompt_bgm, guidance_scale=1.5, num_steps=steps, disable_progress=disable_progress)
301
- return wave
302
-
303
- def to(self, device=None, dtype=None, non_blocking=False):
304
- if device is not None:
305
- self.device = device
306
- self.model.device = device
307
- self.vae = self.vae.to(device, dtype, non_blocking)
308
- self.model = self.model.to(device, dtype, non_blocking)
309
- return self
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/fsq/fsq.py DELETED
@@ -1,236 +0,0 @@
1
- """
2
- Finite Scalar Quantization: VQ-VAE Made Simple - https://arxiv.org/abs/2309.15505
3
- Code adapted from Jax version in Appendix A.1
4
- """
5
-
6
- from __future__ import annotations
7
- from functools import wraps, partial
8
- from contextlib import nullcontext
9
- from typing import List, Tuple
10
-
11
- import torch
12
- import torch.nn as nn
13
- from torch.nn import Module
14
- from torch import Tensor, int32
15
- from torch.amp import autocast
16
-
17
- from einops import rearrange, pack, unpack
18
-
19
- # helper functions
20
-
21
- def exists(v):
22
- return v is not None
23
-
24
- def default(*args):
25
- for arg in args:
26
- if exists(arg):
27
- return arg
28
- return None
29
-
30
- def maybe(fn):
31
- @wraps(fn)
32
- def inner(x, *args, **kwargs):
33
- if not exists(x):
34
- return x
35
- return fn(x, *args, **kwargs)
36
- return inner
37
-
38
- def pack_one(t, pattern):
39
- return pack([t], pattern)
40
-
41
- def unpack_one(t, ps, pattern):
42
- return unpack(t, ps, pattern)[0]
43
-
44
- # tensor helpers
45
-
46
- def round_ste(z: Tensor) -> Tensor:
47
- """Round with straight through gradients."""
48
- zhat = z.round()
49
- return z + (zhat - z).detach()
50
-
51
- # main class
52
-
53
- class FSQ(Module):
54
- def __init__(
55
- self,
56
- levels: List[int],
57
- dim: int | None = None,
58
- num_codebooks = 1,
59
- keep_num_codebooks_dim: bool | None = None,
60
- scale: float | None = None,
61
- allowed_dtypes: Tuple[torch.dtype, ...] = (torch.float32, torch.float64),
62
- channel_first: bool = False,
63
- projection_has_bias: bool = True,
64
- return_indices = True,
65
- force_quantization_f32 = True
66
- ):
67
- super().__init__()
68
- _levels = torch.tensor(levels, dtype=int32)
69
- self.register_buffer("_levels", _levels, persistent = False)
70
-
71
- _basis = torch.cumprod(torch.tensor([1] + levels[:-1]), dim=0, dtype=int32)
72
- self.register_buffer("_basis", _basis, persistent = False)
73
-
74
- self.scale = scale
75
-
76
- codebook_dim = len(levels)
77
- self.codebook_dim = codebook_dim
78
-
79
- effective_codebook_dim = codebook_dim * num_codebooks
80
- self.num_codebooks = num_codebooks
81
- self.effective_codebook_dim = effective_codebook_dim
82
-
83
- keep_num_codebooks_dim = default(keep_num_codebooks_dim, num_codebooks > 1)
84
- assert not (num_codebooks > 1 and not keep_num_codebooks_dim)
85
- self.keep_num_codebooks_dim = keep_num_codebooks_dim
86
-
87
- self.dim = default(dim, len(_levels) * num_codebooks)
88
-
89
- self.channel_first = channel_first
90
-
91
- has_projections = self.dim != effective_codebook_dim
92
- self.project_in = nn.Linear(self.dim, effective_codebook_dim, bias = projection_has_bias) if has_projections else nn.Identity()
93
- self.project_out = nn.Linear(effective_codebook_dim, self.dim, bias = projection_has_bias) if has_projections else nn.Identity()
94
-
95
- self.has_projections = has_projections
96
-
97
- self.return_indices = return_indices
98
- if return_indices:
99
- self.codebook_size = self._levels.prod().item()
100
- implicit_codebook = self._indices_to_codes(torch.arange(self.codebook_size))
101
- self.register_buffer("implicit_codebook", implicit_codebook, persistent = False)
102
-
103
- self.allowed_dtypes = allowed_dtypes
104
- self.force_quantization_f32 = force_quantization_f32
105
-
106
- def bound(self, z, eps: float = 1e-3):
107
- """ Bound `z`, an array of shape (..., d). """
108
- half_l = (self._levels - 1) * (1 + eps) / 2
109
- offset = torch.where(self._levels % 2 == 0, 0.5, 0.0)
110
- shift = (offset / half_l).atanh()
111
- return (z + shift).tanh() * half_l - offset
112
-
113
- def quantize(self, z):
114
- """ Quantizes z, returns quantized zhat, same shape as z. """
115
- quantized = round_ste(self.bound(z))
116
- half_width = self._levels // 2 # Renormalize to [-1, 1].
117
- return quantized / half_width
118
-
119
- def _scale_and_shift(self, zhat_normalized):
120
- half_width = self._levels // 2
121
- return (zhat_normalized * half_width) + half_width
122
-
123
- def _scale_and_shift_inverse(self, zhat):
124
- half_width = self._levels // 2
125
- return (zhat - half_width) / half_width
126
-
127
- def _indices_to_codes(self, indices):
128
- level_indices = self.indices_to_level_indices(indices)
129
- codes = self._scale_and_shift_inverse(level_indices)
130
- return codes
131
-
132
- def codes_to_indices(self, zhat):
133
- """ Converts a `code` to an index in the codebook. """
134
- assert zhat.shape[-1] == self.codebook_dim
135
- zhat = self._scale_and_shift(zhat)
136
- return (zhat * self._basis).sum(dim=-1).to(int32)
137
-
138
- def indices_to_level_indices(self, indices):
139
- """ Converts indices to indices at each level, perhaps needed for a transformer with factorized embeddings """
140
- indices = rearrange(indices, '... -> ... 1')
141
- codes_non_centered = (indices // self._basis) % self._levels
142
- return codes_non_centered
143
-
144
- def indices_to_codes(self, indices):
145
- """ Inverse of `codes_to_indices`. """
146
- assert exists(indices)
147
-
148
- is_img_or_video = indices.ndim >= (3 + int(self.keep_num_codebooks_dim))
149
-
150
- codes = self._indices_to_codes(indices)
151
-
152
- if self.keep_num_codebooks_dim:
153
- codes = rearrange(codes, '... c d -> ... (c d)')
154
-
155
- codes = self.project_out(codes)
156
-
157
- if is_img_or_video or self.channel_first:
158
- codes = rearrange(codes, 'b ... d -> b d ...')
159
-
160
- return codes
161
-
162
- def forward(self, z):
163
- """
164
- einstein notation
165
- b - batch
166
- n - sequence (or flattened spatial dimensions)
167
- d - feature dimension
168
- c - number of codebook dim
169
- """
170
-
171
- is_img_or_video = z.ndim >= 4
172
- need_move_channel_last = is_img_or_video or self.channel_first
173
-
174
- # standardize image or video into (batch, seq, dimension)
175
-
176
- if need_move_channel_last:
177
- z = rearrange(z, 'b d ... -> b ... d')
178
- z, ps = pack_one(z, 'b * d')
179
-
180
- assert z.shape[-1] == self.dim, f'expected dimension of {self.dim} but found dimension of {z.shape[-1]}'
181
-
182
- z = self.project_in(z)
183
-
184
- z = rearrange(z, 'b n (c d) -> b n c d', c = self.num_codebooks)
185
-
186
- # whether to force quantization step to be full precision or not
187
-
188
- force_f32 = self.force_quantization_f32
189
- quantization_context = partial(autocast, 'cuda', enabled = False) if force_f32 else nullcontext
190
-
191
- with quantization_context():
192
- orig_dtype = z.dtype
193
-
194
- if force_f32 and orig_dtype not in self.allowed_dtypes:
195
- z = z.float()
196
-
197
- codes = self.quantize(z)
198
-
199
- # returning indices could be optional
200
-
201
- indices = None
202
-
203
- if self.return_indices:
204
- indices = self.codes_to_indices(codes)
205
-
206
- codes = rearrange(codes, 'b n c d -> b n (c d)')
207
-
208
- codes = codes.type(orig_dtype)
209
-
210
- # project out
211
-
212
- out = self.project_out(codes)
213
-
214
- # reconstitute image or video dimensions
215
-
216
- if need_move_channel_last:
217
- out = unpack_one(out, ps, 'b * d')
218
- out = rearrange(out, 'b ... d -> b d ...')
219
-
220
- indices = maybe(unpack_one)(indices, ps, 'b * c')
221
-
222
- if not self.keep_num_codebooks_dim and self.return_indices:
223
- indices = maybe(rearrange)(indices, '... 1 -> ...')
224
-
225
- # return quantized output and indices
226
-
227
- return out, indices
228
-
229
-
230
- if __name__ == '__main__':
231
- # test
232
- fsq = FSQ([4, 4, 4],dim=1024)
233
- z = torch.randn(2, 3, 1024)
234
- out, indices = fsq(z)
235
- print(out.shape, indices.shape)
236
- # print(out, indices)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/core_vq.py DELETED
@@ -1,366 +0,0 @@
1
- # Copyright (c) Meta Platforms, Inc. and affiliates.
2
- # All rights reserved.
3
- #
4
- # This source code is licensed under the license found in the
5
- # LICENSE file in the root directory of this source tree.
6
- #
7
- # This implementation is inspired from
8
- # https://github.com/lucidrains/vector-quantize-pytorch
9
- # which is released under MIT License. Hereafter, the original license:
10
- # MIT License
11
- #
12
- # Copyright (c) 2020 Phil Wang
13
- #
14
- # Permission is hereby granted, free of charge, to any person obtaining a copy
15
- # of this software and associated documentation files (the "Software"), to deal
16
- # in the Software without restriction, including without limitation the rights
17
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
- # copies of the Software, and to permit persons to whom the Software is
19
- # furnished to do so, subject to the following conditions:
20
- #
21
- # The above copyright notice and this permission notice shall be included in all
22
- # copies or substantial portions of the Software.
23
- #
24
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
- # SOFTWARE.
31
-
32
- """Core vector quantization implementation."""
33
-
34
- import typing as tp
35
-
36
- from einops import rearrange, repeat
37
- import torch
38
- from torch import nn
39
- import torch.nn.functional as F
40
-
41
- # from .. import distrib
42
-
43
-
44
- def default(val: tp.Any, d: tp.Any) -> tp.Any:
45
- return val if val is not None else d
46
-
47
-
48
- def ema_inplace(moving_avg, new, decay: float):
49
- moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))
50
-
51
-
52
- def laplace_smoothing(x, n_categories: int, epsilon: float = 1e-5):
53
- return (x + epsilon) / (x.sum() + n_categories * epsilon)
54
-
55
-
56
- def uniform_init(*shape: int):
57
- t = torch.empty(shape)
58
- nn.init.kaiming_uniform_(t)
59
- return t
60
-
61
-
62
- def sample_vectors(samples, num: int):
63
- num_samples, device = samples.shape[0], samples.device
64
-
65
- if num_samples >= num:
66
- indices = torch.randperm(num_samples, device=device)[:num]
67
- else:
68
- indices = torch.randint(0, num_samples, (num,), device=device)
69
-
70
- return samples[indices]
71
-
72
-
73
- def kmeans(samples, num_clusters: int, num_iters: int = 10):
74
- dim, dtype = samples.shape[-1], samples.dtype
75
-
76
- means = sample_vectors(samples, num_clusters)
77
-
78
- for _ in range(num_iters):
79
- diffs = rearrange(samples, "n d -> n () d") - rearrange(
80
- means, "c d -> () c d"
81
- )
82
- dists = -(diffs ** 2).sum(dim=-1)
83
-
84
- buckets = dists.max(dim=-1).indices
85
- bins = torch.bincount(buckets, minlength=num_clusters)
86
- zero_mask = bins == 0
87
- bins_min_clamped = bins.masked_fill(zero_mask, 1)
88
-
89
- new_means = buckets.new_zeros(num_clusters, dim, dtype=dtype)
90
- new_means.scatter_add_(0, repeat(buckets, "n -> n d", d=dim), samples)
91
- new_means = new_means / bins_min_clamped[..., None]
92
-
93
- means = torch.where(zero_mask[..., None], means, new_means)
94
-
95
- return means, bins
96
-
97
-
98
- class EuclideanCodebook(nn.Module):
99
- """Codebook with Euclidean distance.
100
- Args:
101
- dim (int): Dimension.
102
- codebook_size (int): Codebook size.
103
- kmeans_init (bool): Whether to use k-means to initialize the codebooks.
104
- If set to true, run the k-means algorithm on the first training batch and use
105
- the learned centroids as initialization.
106
- kmeans_iters (int): Number of iterations used for k-means algorithm at initialization.
107
- decay (float): Decay for exponential moving average over the codebooks.
108
- epsilon (float): Epsilon value for numerical stability.
109
- threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
110
- that have an exponential moving average cluster size less than the specified threshold with
111
- randomly selected vector from the current batch.
112
- """
113
- def __init__(
114
- self,
115
- dim: int,
116
- codebook_size: int,
117
- kmeans_init: int = False,
118
- kmeans_iters: int = 10,
119
- decay: float = 0.99,
120
- epsilon: float = 1e-5,
121
- threshold_ema_dead_code: int = 2,
122
- ):
123
- super().__init__()
124
- self.decay = decay
125
- init_fn: tp.Union[tp.Callable[..., torch.Tensor], tp.Any] = uniform_init if not kmeans_init else torch.zeros
126
- embed = init_fn(codebook_size, dim)
127
-
128
- self.codebook_size = codebook_size
129
-
130
- self.kmeans_iters = kmeans_iters
131
- self.epsilon = epsilon
132
- self.threshold_ema_dead_code = threshold_ema_dead_code
133
-
134
- self.register_buffer("inited", torch.Tensor([not kmeans_init]))
135
- self.register_buffer("cluster_size", torch.zeros(codebook_size))
136
- self.register_buffer("embed", embed)
137
- self.register_buffer("embed_avg", embed.clone())
138
-
139
- self.runed_steps = 0
140
- self.stop_steps = 50_000
141
-
142
- @torch.jit.ignore
143
- def init_embed_(self, data):
144
- if self.inited:
145
- return
146
-
147
- embed, cluster_size = kmeans(data, self.codebook_size, self.kmeans_iters)
148
- self.embed.data.copy_(embed)
149
- self.embed_avg.data.copy_(embed.clone())
150
- self.cluster_size.data.copy_(cluster_size)
151
- self.inited.data.copy_(torch.Tensor([True]))
152
- # Make sure all buffers across workers are in sync after initialization
153
- distrib.broadcast_tensors(self.buffers())
154
-
155
- def replace_(self, samples, mask):
156
- modified_codebook = torch.where(
157
- mask[..., None], sample_vectors(samples, self.codebook_size), self.embed
158
- )
159
- self.embed.data.copy_(modified_codebook)
160
-
161
- def expire_codes_(self, batch_samples):
162
- if self.threshold_ema_dead_code == 0:
163
- return
164
-
165
- expired_codes = self.cluster_size < self.threshold_ema_dead_code
166
- if not torch.any(expired_codes):
167
- return
168
-
169
- batch_samples = rearrange(batch_samples, "... d -> (...) d")
170
- self.replace_(batch_samples, mask=expired_codes)
171
- # distrib.broadcast_tensors(self.buffers())
172
-
173
- def preprocess(self, x):
174
- x = rearrange(x, "... d -> (...) d")
175
- return x
176
-
177
- def quantize(self, x):
178
- embed = self.embed.t()
179
- dist = -(
180
- x.pow(2).sum(1, keepdim=True)
181
- - 2 * x @ embed
182
- + embed.pow(2).sum(0, keepdim=True)
183
- )
184
- embed_ind = dist.max(dim=-1).indices
185
- return embed_ind
186
-
187
- def postprocess_emb(self, embed_ind, shape):
188
- return embed_ind.view(*shape[:-1])
189
-
190
- def dequantize(self, embed_ind):
191
- quantize = F.embedding(embed_ind, self.embed)
192
- return quantize
193
-
194
- def encode(self, x):
195
- shape = x.shape
196
- # pre-process
197
- x = self.preprocess(x)
198
- # quantize
199
- embed_ind = self.quantize(x)
200
- # post-process
201
- embed_ind = self.postprocess_emb(embed_ind, shape)
202
- return embed_ind
203
-
204
- def decode(self, embed_ind):
205
- quantize = self.dequantize(embed_ind)
206
- return quantize
207
-
208
- def forward(self, x):
209
- shape, dtype = x.shape, x.dtype
210
- x = self.preprocess(x)
211
- # self.init_embed_(x)
212
-
213
- embed_ind = self.quantize(x)
214
- embed_onehot = F.one_hot(embed_ind, self.codebook_size).type(dtype)
215
- embed_ind = self.postprocess_emb(embed_ind, shape)
216
- quantize = self.dequantize(embed_ind)
217
- self.runed_steps += 1
218
-
219
- if self.training and self.runed_steps < self.stop_steps:
220
- # We do the expiry of code at that point as buffers are in sync
221
- # and all the workers will take the same decision.
222
- self.expire_codes_(x)
223
- ema_inplace(self.cluster_size, embed_onehot.sum(0), self.decay)
224
- embed_sum = x.t() @ embed_onehot
225
- ema_inplace(self.embed_avg, embed_sum.t(), self.decay)
226
- cluster_size = (
227
- laplace_smoothing(self.cluster_size, self.codebook_size, self.epsilon)
228
- * self.cluster_size.sum()
229
- )
230
- embed_normalized = self.embed_avg / cluster_size.unsqueeze(1)
231
- self.embed.data.copy_(embed_normalized)
232
-
233
- return quantize, embed_ind
234
-
235
-
236
- class VectorQuantization(nn.Module):
237
- """Vector quantization implementation.
238
- Currently supports only euclidean distance.
239
- Args:
240
- dim (int): Dimension
241
- codebook_size (int): Codebook size
242
- codebook_dim (int): Codebook dimension. If not defined, uses the specified dimension in dim.
243
- decay (float): Decay for exponential moving average over the codebooks.
244
- epsilon (float): Epsilon value for numerical stability.
245
- kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
246
- kmeans_iters (int): Number of iterations used for kmeans initialization.
247
- threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
248
- that have an exponential moving average cluster size less than the specified threshold with
249
- randomly selected vector from the current batch.
250
- commitment_weight (float): Weight for commitment loss.
251
- """
252
- def __init__(
253
- self,
254
- dim: int,
255
- codebook_size: int,
256
- codebook_dim: tp.Optional[int] = None,
257
- decay: float = 0.99,
258
- epsilon: float = 1e-5,
259
- kmeans_init: bool = True,
260
- kmeans_iters: int = 50,
261
- threshold_ema_dead_code: int = 2,
262
- commitment_weight: float = 1.,
263
- ):
264
- super().__init__()
265
- _codebook_dim: int = default(codebook_dim, dim)
266
-
267
- requires_projection = _codebook_dim != dim
268
- self.project_in = (nn.Linear(dim, _codebook_dim) if requires_projection else nn.Identity())
269
- self.project_out = (nn.Linear(_codebook_dim, dim) if requires_projection else nn.Identity())
270
-
271
- self.epsilon = epsilon
272
- self.commitment_weight = commitment_weight
273
-
274
- self._codebook = EuclideanCodebook(dim=_codebook_dim, codebook_size=codebook_size,
275
- kmeans_init=kmeans_init, kmeans_iters=kmeans_iters,
276
- decay=decay, epsilon=epsilon,
277
- threshold_ema_dead_code=threshold_ema_dead_code)
278
- self.codebook_size = codebook_size
279
-
280
- @property
281
- def codebook(self):
282
- return self._codebook.embed
283
-
284
- def encode(self, x):
285
- x = rearrange(x, "b d n -> b n d")
286
- x = self.project_in(x)
287
- embed_in = self._codebook.encode(x)
288
- return embed_in
289
-
290
- def decode(self, embed_ind):
291
- quantize = self._codebook.decode(embed_ind)
292
- quantize = self.project_out(quantize)
293
- quantize = rearrange(quantize, "b n d -> b d n")
294
- return quantize
295
-
296
- def forward(self, x, do_debug=False):
297
- device = x.device
298
- x = rearrange(x, "b d n -> b n d")
299
- x = self.project_in(x)
300
-
301
- quantize, embed_ind = self._codebook(x)
302
-
303
- if self.training:
304
- quantize = x + (quantize - x).detach()
305
-
306
- loss = torch.tensor([0.0], device=device, requires_grad=self.training)
307
-
308
- if self.training:
309
- if self.commitment_weight > 0:
310
- commit_loss = F.mse_loss(quantize.detach(), x)
311
- loss = loss + commit_loss * self.commitment_weight
312
- quantize = self.project_out(quantize)
313
- quantize = rearrange(quantize, "b n d -> b d n")
314
- return quantize, embed_ind, loss
315
-
316
-
317
- class ResidualVectorQuantization(nn.Module):
318
- """Residual vector quantization implementation.
319
- Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf
320
- """
321
- def __init__(self, *, num_quantizers, **kwargs):
322
- super().__init__()
323
- self.layers = nn.ModuleList(
324
- [VectorQuantization(**kwargs) for _ in range(num_quantizers)]
325
- )
326
-
327
- def forward(self, x, n_q: tp.Optional[int] = None):
328
- quantized_out = 0.0
329
- residual = x
330
-
331
- all_losses = []
332
- all_indices = []
333
-
334
- n_q = n_q or len(self.layers)
335
-
336
- for layerinx, layer in enumerate(self.layers[:n_q]):
337
- print("Layer {} Used ratio {:.1f}".format(layerinx, (layer._codebook.cluster_size > 1.0).sum() / layer._codebook.cluster_size.shape[0] * 100.))
338
- quantized, indices, loss = layer(residual)
339
- residual = residual - quantized
340
- quantized_out = quantized_out + quantized
341
-
342
- all_indices.append(indices)
343
- all_losses.append(loss)
344
-
345
- out_losses, out_indices = map(torch.stack, (all_losses, all_indices))
346
- return quantized_out, out_indices, out_losses
347
-
348
- def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None) -> torch.Tensor:
349
- residual = x
350
- all_indices = []
351
- n_q = n_q or len(self.layers)
352
- for layer in self.layers[:n_q]:
353
- indices = layer.encode(residual)
354
- quantized = layer.decode(indices)
355
- residual = residual - quantized
356
- all_indices.append(indices)
357
- out_indices = torch.stack(all_indices)
358
- return out_indices
359
-
360
- def decode(self, q_indices: torch.Tensor) -> torch.Tensor:
361
- quantized_out = torch.tensor(0.0, device=q_indices.device)
362
- for i, indices in enumerate(q_indices):
363
- layer = self.layers[i]
364
- quantized = layer.decode(indices)
365
- quantized_out = quantized_out + quantized
366
- return quantized_out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize.py DELETED
@@ -1,268 +0,0 @@
1
- from typing import Union
2
-
3
- import numpy as np
4
- import torch
5
- import torch.nn as nn
6
- import torch.nn.functional as F
7
- from einops import rearrange
8
- from torch.nn.utils import weight_norm
9
-
10
- def WNConv1d(*args, **kwargs):
11
- return weight_norm(nn.Conv1d(*args, **kwargs))
12
-
13
- class VectorQuantize(nn.Module):
14
- """
15
- Implementation of VQ similar to Karpathy's repo:
16
- https://github.com/karpathy/deep-vector-quantization
17
- Additionally uses following tricks from Improved VQGAN
18
- (https://arxiv.org/pdf/2110.04627.pdf):
19
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
20
- for improved codebook usage
21
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
22
- improves training stability
23
- """
24
-
25
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int):
26
- super().__init__()
27
- self.codebook_size = codebook_size
28
- self.codebook_dim = codebook_dim
29
-
30
- self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
31
- self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
32
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
33
-
34
- def forward(self, z):
35
- """Quantized the input tensor using a fixed codebook and returns
36
- the corresponding codebook vectors
37
-
38
- Parameters
39
- ----------
40
- z : Tensor[B x D x T]
41
-
42
- Returns
43
- -------
44
- Tensor[B x D x T]
45
- Quantized continuous representation of input
46
- Tensor[1]
47
- Commitment loss to train encoder to predict vectors closer to codebook
48
- entries
49
- Tensor[1]
50
- Codebook loss to update the codebook
51
- Tensor[B x T]
52
- Codebook indices (quantized discrete representation of input)
53
- Tensor[B x D x T]
54
- Projected latents (continuous representation of input before quantization)
55
- """
56
-
57
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
58
- z_e = self.in_proj(z) # z_e : (B x D x T)
59
- z_q, indices = self.decode_latents(z_e)
60
-
61
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
62
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
63
-
64
- z_q = (
65
- z_e + (z_q - z_e).detach()
66
- ) # noop in forward pass, straight-through gradient estimator in backward pass
67
-
68
- z_q = self.out_proj(z_q)
69
-
70
- return z_q, commitment_loss, codebook_loss, indices, z_e
71
-
72
- def embed_code(self, embed_id):
73
- return F.embedding(embed_id, self.codebook.weight)
74
-
75
- def decode_code(self, embed_id):
76
- return self.embed_code(embed_id).transpose(1, 2)
77
-
78
- def decode_latents(self, latents):
79
- encodings = rearrange(latents, "b d t -> (b t) d")
80
- codebook = self.codebook.weight # codebook: (N x D)
81
-
82
- # L2 normalize encodings and codebook (ViT-VQGAN)
83
- encodings = F.normalize(encodings)
84
- codebook = F.normalize(codebook)
85
-
86
- # Compute euclidean distance with codebook
87
- dist = (
88
- encodings.pow(2).sum(1, keepdim=True)
89
- - 2 * encodings @ codebook.t()
90
- + codebook.pow(2).sum(1, keepdim=True).t()
91
- )
92
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
93
- z_q = self.decode_code(indices)
94
- return z_q, indices
95
-
96
-
97
- class ResidualVectorQuantize(nn.Module):
98
- """
99
- Introduced in SoundStream: An end2end neural audio codec
100
- https://arxiv.org/abs/2107.03312
101
- """
102
-
103
- def __init__(
104
- self,
105
- input_dim: int = 512,
106
- n_codebooks: int = 9,
107
- codebook_size: int = 1024,
108
- codebook_dim: Union[int, list] = 8,
109
- quantizer_dropout: float = 0.0,
110
- ):
111
- super().__init__()
112
- if isinstance(codebook_dim, int):
113
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
114
-
115
- self.n_codebooks = n_codebooks
116
- self.codebook_dim = codebook_dim
117
- self.codebook_size = codebook_size
118
-
119
- self.quantizers = nn.ModuleList(
120
- [
121
- VectorQuantize(input_dim, codebook_size, codebook_dim[i])
122
- for i in range(n_codebooks)
123
- ]
124
- )
125
- self.quantizer_dropout = quantizer_dropout
126
-
127
- def forward(self, z, n_quantizers: int = None):
128
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
129
- the corresponding codebook vectors
130
- Parameters
131
- ----------
132
- z : Tensor[B x D x T]
133
- n_quantizers : int, optional
134
- No. of quantizers to use
135
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
136
- Note: if `self.quantizer_dropout` is True, this argument is ignored
137
- when in training mode, and a random number of quantizers is used.
138
- Returns
139
- -------
140
- dict
141
- A dictionary with the following keys:
142
-
143
- "z" : Tensor[B x D x T]
144
- Quantized continuous representation of input
145
- "codes" : Tensor[B x N x T]
146
- Codebook indices for each codebook
147
- (quantized discrete representation of input)
148
- "latents" : Tensor[B x N*D x T]
149
- Projected latents (continuous representation of input before quantization)
150
- "vq/commitment_loss" : Tensor[1]
151
- Commitment loss to train encoder to predict vectors closer to codebook
152
- entries
153
- "vq/codebook_loss" : Tensor[1]
154
- Codebook loss to update the codebook
155
- """
156
- z_q = 0
157
- residual = z
158
- commitment_loss = 0
159
- codebook_loss = 0
160
-
161
- codebook_indices = []
162
- latents = []
163
-
164
- if n_quantizers is None:
165
- n_quantizers = self.n_codebooks
166
- if self.training:
167
- n_quantizers = torch.ones((z.shape[0],)) * self.n_codebooks + 1
168
- dropout = torch.randint(1, self.n_codebooks + 1, (z.shape[0],))
169
- n_dropout = int(z.shape[0] * self.quantizer_dropout)
170
- n_quantizers[:n_dropout] = dropout[:n_dropout]
171
- n_quantizers = n_quantizers.to(z.device)
172
-
173
- for i, quantizer in enumerate(self.quantizers):
174
- if self.training is False and i >= n_quantizers:
175
- break
176
-
177
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
178
- residual
179
- )
180
-
181
- # Create mask to apply quantizer dropout
182
- mask = (
183
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
184
- )
185
- z_q = z_q + z_q_i * mask[:, None, None]
186
- residual = residual - z_q_i
187
-
188
- # Sum losses
189
- commitment_loss += (commitment_loss_i * mask).mean()
190
- codebook_loss += (codebook_loss_i * mask).mean()
191
-
192
- codebook_indices.append(indices_i)
193
- latents.append(z_e_i)
194
-
195
- codes = torch.stack(codebook_indices, dim=1)
196
- latents = torch.cat(latents, dim=1)
197
-
198
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
199
- for n in range(encodings.shape[1]):
200
- print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
201
- (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
202
- ))
203
-
204
- return z_q, codes, latents, commitment_loss, codebook_loss
205
-
206
- def from_codes(self, codes: torch.Tensor):
207
- """Given the quantized codes, reconstruct the continuous representation
208
- Parameters
209
- ----------
210
- codes : Tensor[B x N x T]
211
- Quantized discrete representation of input
212
- Returns
213
- -------
214
- Tensor[B x D x T]
215
- Quantized continuous representation of input
216
- """
217
- z_q = 0.0
218
- z_p = []
219
- n_codebooks = codes.shape[1]
220
- for i in range(n_codebooks):
221
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
222
- z_p.append(z_p_i)
223
-
224
- z_q_i = self.quantizers[i].out_proj(z_p_i)
225
- z_q = z_q + z_q_i
226
- return z_q, torch.cat(z_p, dim=1), codes
227
-
228
- def from_latents(self, latents: torch.Tensor):
229
- """Given the unquantized latents, reconstruct the
230
- continuous representation after quantization.
231
-
232
- Parameters
233
- ----------
234
- latents : Tensor[B x N x T]
235
- Continuous representation of input after projection
236
-
237
- Returns
238
- -------
239
- Tensor[B x D x T]
240
- Quantized representation of full-projected space
241
- Tensor[B x D x T]
242
- Quantized representation of latent space
243
- """
244
- z_q = 0
245
- z_p = []
246
- codes = []
247
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
248
-
249
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
250
- 0
251
- ]
252
- for i in range(n_codebooks):
253
- j, k = dims[i], dims[i + 1]
254
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
255
- z_p.append(z_p_i)
256
- codes.append(codes_i)
257
-
258
- z_q_i = self.quantizers[i].out_proj(z_p_i)
259
- z_q = z_q + z_q_i
260
-
261
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
262
-
263
-
264
- if __name__ == "__main__":
265
- rvq = ResidualVectorQuantize(quantizer_dropout=True)
266
- x = torch.randn(16, 512, 80)
267
- y = rvq(x)
268
- print(y["latents"].shape)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize2.py DELETED
@@ -1,290 +0,0 @@
1
- from typing import Union
2
-
3
- import numpy as np
4
- import torch
5
- import torch.nn as nn
6
- import torch.nn.functional as F
7
- from einops import rearrange
8
- from torch.nn.utils import weight_norm
9
-
10
- def WNConv1d(*args, **kwargs):
11
- return weight_norm(nn.Conv1d(*args, **kwargs))
12
-
13
- class VectorQuantize(nn.Module):
14
- """
15
- Implementation of VQ similar to Karpathy's repo:
16
- https://github.com/karpathy/deep-vector-quantization
17
- Additionally uses following tricks from Improved VQGAN
18
- (https://arxiv.org/pdf/2110.04627.pdf):
19
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
20
- for improved codebook usage
21
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
22
- improves training stability
23
- """
24
-
25
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, stale_tolerance: int = 100):
26
- super().__init__()
27
- self.codebook_size = codebook_size
28
- self.codebook_dim = codebook_dim
29
-
30
- self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
31
- self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
32
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
33
- self.register_buffer("stale_counter", torch.zeros(self.codebook_size,))
34
- self.stale_tolerance = stale_tolerance
35
-
36
- def forward(self, z):
37
- """Quantized the input tensor using a fixed codebook and returns
38
- the corresponding codebook vectors
39
-
40
- Parameters
41
- ----------
42
- z : Tensor[B x D x T]
43
-
44
- Returns
45
- -------
46
- Tensor[B x D x T]
47
- Quantized continuous representation of input
48
- Tensor[1]
49
- Commitment loss to train encoder to predict vectors closer to codebook
50
- entries
51
- Tensor[1]
52
- Codebook loss to update the codebook
53
- Tensor[B x T]
54
- Codebook indices (quantized discrete representation of input)
55
- Tensor[B x D x T]
56
- Projected latents (continuous representation of input before quantization)
57
- """
58
-
59
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
60
- z_e = self.in_proj(z) # z_e : (B x D x T)
61
- z_q, indices = self.decode_latents(z_e)
62
-
63
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
64
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
65
-
66
- z_q = (
67
- z_e + (z_q - z_e).detach()
68
- ) # noop in forward pass, straight-through gradient estimator in backward pass
69
-
70
- z_q = self.out_proj(z_q)
71
-
72
- return z_q, commitment_loss, codebook_loss, indices, z_e
73
-
74
- def embed_code(self, embed_id):
75
- return F.embedding(embed_id, self.codebook.weight)
76
-
77
- def decode_code(self, embed_id):
78
- return self.embed_code(embed_id).transpose(1, 2)
79
-
80
- def decode_latents(self, latents):
81
- encodings = rearrange(latents, "b d t -> (b t) d")
82
- codebook = self.codebook.weight # codebook: (N x D)
83
-
84
- # L2 normalize encodings and codebook (ViT-VQGAN)
85
- encodings = F.normalize(encodings)
86
- codebook = F.normalize(codebook)
87
-
88
- # Compute euclidean distance with codebook
89
- dist = (
90
- encodings.pow(2).sum(1, keepdim=True)
91
- - 2 * encodings @ codebook.t()
92
- + codebook.pow(2).sum(1, keepdim=True).t()
93
- )
94
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
95
- z_q = self.decode_code(indices)
96
-
97
- if(self.training):
98
- onehots = torch.nn.functional.one_hot(indices, self.codebook_size).float() # B, T, codebook_size
99
- stale_codes = (onehots.sum(0).sum(0) == 0).float()
100
- self.stale_counter = self.stale_counter * stale_codes + stale_codes
101
-
102
- # random replace codes that haven't been used for a while
103
- replace_code = (self.stale_counter == self.stale_tolerance).float() # codebook_size
104
- if replace_code.sum(-1) > 0:
105
- print("Replace {} codes".format(replace_code.sum(-1)))
106
- random_input_idx = torch.randperm(encodings.shape[0])
107
- random_input = encodings[random_input_idx].view(encodings.shape)
108
- if random_input.shape[0] < self.codebook_size:
109
- random_input = torch.cat([random_input]*(self.codebook_size // random_input.shape[0] + 1), 0)
110
- random_input = random_input[:self.codebook_size,:].contiguous() # codebook_size, dim
111
-
112
- self.codebook.weight.data = self.codebook.weight.data * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
113
- self.stale_counter = self.stale_counter * (1 - replace_code)
114
-
115
- return z_q, indices
116
-
117
-
118
- class ResidualVectorQuantize(nn.Module):
119
- """
120
- Introduced in SoundStream: An end2end neural audio codec
121
- https://arxiv.org/abs/2107.03312
122
- """
123
-
124
- def __init__(
125
- self,
126
- input_dim: int = 512,
127
- n_codebooks: int = 9,
128
- codebook_size: int = 1024,
129
- codebook_dim: Union[int, list] = 8,
130
- quantizer_dropout: float = 0.0,
131
- stale_tolerance: int = 100,
132
- ):
133
- super().__init__()
134
- if isinstance(codebook_dim, int):
135
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
136
-
137
- self.n_codebooks = n_codebooks
138
- self.codebook_dim = codebook_dim
139
- self.codebook_size = codebook_size
140
-
141
- self.quantizers = nn.ModuleList(
142
- [
143
- VectorQuantize(input_dim, codebook_size, codebook_dim[i], stale_tolerance=stale_tolerance)
144
- for i in range(n_codebooks)
145
- ]
146
- )
147
- self.quantizer_dropout = quantizer_dropout
148
-
149
- def forward(self, z, n_quantizers: int = None):
150
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
151
- the corresponding codebook vectors
152
- Parameters
153
- ----------
154
- z : Tensor[B x D x T]
155
- n_quantizers : int, optional
156
- No. of quantizers to use
157
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
158
- Note: if `self.quantizer_dropout` is True, this argument is ignored
159
- when in training mode, and a random number of quantizers is used.
160
- Returns
161
- -------
162
- dict
163
- A dictionary with the following keys:
164
-
165
- "z" : Tensor[B x D x T]
166
- Quantized continuous representation of input
167
- "codes" : Tensor[B x N x T]
168
- Codebook indices for each codebook
169
- (quantized discrete representation of input)
170
- "latents" : Tensor[B x N*D x T]
171
- Projected latents (continuous representation of input before quantization)
172
- "vq/commitment_loss" : Tensor[1]
173
- Commitment loss to train encoder to predict vectors closer to codebook
174
- entries
175
- "vq/codebook_loss" : Tensor[1]
176
- Codebook loss to update the codebook
177
- """
178
- z_q = 0
179
- residual = z
180
- commitment_loss = 0
181
- codebook_loss = 0
182
-
183
- codebook_indices = []
184
- latents = []
185
-
186
- if n_quantizers is None:
187
- n_quantizers = self.n_codebooks
188
- if self.training:
189
- n_quantizers = torch.ones((z.shape[0],)) * self.n_codebooks + 1
190
- dropout = torch.randint(1, self.n_codebooks + 1, (z.shape[0],))
191
- n_dropout = int(z.shape[0] * self.quantizer_dropout)
192
- n_quantizers[:n_dropout] = dropout[:n_dropout]
193
- n_quantizers = n_quantizers.to(z.device)
194
-
195
- for i, quantizer in enumerate(self.quantizers):
196
- if self.training is False and i >= n_quantizers:
197
- break
198
-
199
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
200
- residual
201
- )
202
-
203
- # Create mask to apply quantizer dropout
204
- mask = (
205
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
206
- )
207
- z_q = z_q + z_q_i * mask[:, None, None]
208
- residual = residual - z_q_i
209
-
210
- # Sum losses
211
- commitment_loss += (commitment_loss_i * mask).mean()
212
- codebook_loss += (codebook_loss_i * mask).mean()
213
-
214
- codebook_indices.append(indices_i)
215
- latents.append(z_e_i)
216
-
217
- codes = torch.stack(codebook_indices, dim=1)
218
- latents = torch.cat(latents, dim=1)
219
-
220
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
221
- for n in range(encodings.shape[1]):
222
- print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
223
- (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
224
- ))
225
-
226
- return z_q, codes, latents, commitment_loss, codebook_loss
227
-
228
- def from_codes(self, codes: torch.Tensor):
229
- """Given the quantized codes, reconstruct the continuous representation
230
- Parameters
231
- ----------
232
- codes : Tensor[B x N x T]
233
- Quantized discrete representation of input
234
- Returns
235
- -------
236
- Tensor[B x D x T]
237
- Quantized continuous representation of input
238
- """
239
- z_q = 0.0
240
- z_p = []
241
- n_codebooks = codes.shape[1]
242
- for i in range(n_codebooks):
243
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
244
- z_p.append(z_p_i)
245
-
246
- z_q_i = self.quantizers[i].out_proj(z_p_i)
247
- z_q = z_q + z_q_i
248
- return z_q, torch.cat(z_p, dim=1), codes
249
-
250
- def from_latents(self, latents: torch.Tensor):
251
- """Given the unquantized latents, reconstruct the
252
- continuous representation after quantization.
253
-
254
- Parameters
255
- ----------
256
- latents : Tensor[B x N x T]
257
- Continuous representation of input after projection
258
-
259
- Returns
260
- -------
261
- Tensor[B x D x T]
262
- Quantized representation of full-projected space
263
- Tensor[B x D x T]
264
- Quantized representation of latent space
265
- """
266
- z_q = 0
267
- z_p = []
268
- codes = []
269
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
270
-
271
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
272
- 0
273
- ]
274
- for i in range(n_codebooks):
275
- j, k = dims[i], dims[i + 1]
276
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
277
- z_p.append(z_p_i)
278
- codes.append(codes_i)
279
-
280
- z_q_i = self.quantizers[i].out_proj(z_p_i)
281
- z_q = z_q + z_q_i
282
-
283
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
284
-
285
-
286
- if __name__ == "__main__":
287
- rvq = ResidualVectorQuantize(quantizer_dropout=True)
288
- x = torch.randn(16, 512, 80)
289
- y = rvq(x)
290
- print(y["latents"].shape)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_4layer.py DELETED
@@ -1,303 +0,0 @@
1
- # compared with `descript_quantize2`, we use rvq & random_dropout
2
- from typing import Union
3
-
4
- import numpy as np
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from einops import rearrange
9
- from torch.nn.utils import weight_norm
10
- import random
11
-
12
- def WNConv1d(*args, **kwargs):
13
- return weight_norm(nn.Conv1d(*args, **kwargs))
14
-
15
- class VectorQuantize(nn.Module):
16
- """
17
- Implementation of VQ similar to Karpathy's repo:
18
- https://github.com/karpathy/deep-vector-quantization
19
- Additionally uses following tricks from Improved VQGAN
20
- (https://arxiv.org/pdf/2110.04627.pdf):
21
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
22
- for improved codebook usage
23
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
24
- improves training stability
25
- """
26
-
27
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, stale_tolerance: int = 100):
28
- super().__init__()
29
- self.codebook_size = codebook_size
30
- self.codebook_dim = codebook_dim
31
-
32
- self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
33
- self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
34
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
35
- self.register_buffer("stale_counter", torch.zeros(self.codebook_size,))
36
- self.stale_tolerance = stale_tolerance
37
-
38
- def forward(self, z):
39
- """Quantized the input tensor using a fixed codebook and returns
40
- the corresponding codebook vectors
41
-
42
- Parameters
43
- ----------
44
- z : Tensor[B x D x T]
45
-
46
- Returns
47
- -------
48
- Tensor[B x D x T]
49
- Quantized continuous representation of input
50
- Tensor[1]
51
- Commitment loss to train encoder to predict vectors closer to codebook
52
- entries
53
- Tensor[1]
54
- Codebook loss to update the codebook
55
- Tensor[B x T]
56
- Codebook indices (quantized discrete representation of input)
57
- Tensor[B x D x T]
58
- Projected latents (continuous representation of input before quantization)
59
- """
60
-
61
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
62
- z_e = self.in_proj(z) # z_e : (B x D x T)
63
- z_q, indices = self.decode_latents(z_e)
64
-
65
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
66
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
67
-
68
- z_q = (
69
- z_e + (z_q - z_e).detach()
70
- ) # noop in forward pass, straight-through gradient estimator in backward pass
71
-
72
- z_q = self.out_proj(z_q)
73
-
74
- return z_q, commitment_loss, codebook_loss, indices, z_e
75
-
76
- def embed_code(self, embed_id):
77
- return F.embedding(embed_id, self.codebook.weight)
78
-
79
- def decode_code(self, embed_id):
80
- return self.embed_code(embed_id).transpose(1, 2)
81
-
82
- def decode_latents(self, latents):
83
- encodings = rearrange(latents, "b d t -> (b t) d")
84
- codebook = self.codebook.weight # codebook: (N x D)
85
-
86
- # L2 normalize encodings and codebook (ViT-VQGAN)
87
- encodings = F.normalize(encodings)
88
- codebook = F.normalize(codebook)
89
-
90
- # Compute euclidean distance with codebook
91
- dist = (
92
- encodings.pow(2).sum(1, keepdim=True)
93
- - 2 * encodings @ codebook.t()
94
- + codebook.pow(2).sum(1, keepdim=True).t()
95
- )
96
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
97
- z_q = self.decode_code(indices)
98
-
99
- if(self.training):
100
- onehots = torch.nn.functional.one_hot(indices, self.codebook_size).float() # B, T, codebook_size
101
- stale_codes = (onehots.sum(0).sum(0) == 0).float()
102
- self.stale_counter = self.stale_counter * stale_codes + stale_codes
103
-
104
- # random replace codes that haven't been used for a while
105
- replace_code = (self.stale_counter == self.stale_tolerance).float() # codebook_size
106
- if replace_code.sum(-1) > 0:
107
- print("Replace {} codes".format(replace_code.sum(-1)))
108
- random_input_idx = torch.randperm(encodings.shape[0])
109
- random_input = encodings[random_input_idx].view(encodings.shape)
110
- if random_input.shape[0] < self.codebook_size:
111
- random_input = torch.cat([random_input]*(self.codebook_size // random_input.shape[0] + 1), 0)
112
- random_input = random_input[:self.codebook_size,:].contiguous() # codebook_size, dim
113
-
114
- self.codebook.weight.data = self.codebook.weight.data * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
115
- self.stale_counter = self.stale_counter * (1 - replace_code)
116
-
117
- return z_q, indices
118
-
119
-
120
- class ResidualVectorQuantize(nn.Module):
121
- """
122
- Introduced in SoundStream: An end2end neural audio codec
123
- https://arxiv.org/abs/2107.03312
124
- """
125
-
126
- def __init__(
127
- self,
128
- input_dim: int = 512,
129
- n_codebooks: int = 9,
130
- codebook_size: int = 1024,
131
- codebook_dim: Union[int, list] = 8,
132
- quantizer_dropout: float = 0.0,
133
- stale_tolerance: int = 100,
134
- ):
135
- super().__init__()
136
- if isinstance(codebook_dim, int):
137
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
138
-
139
- self.n_codebooks = n_codebooks
140
- self.codebook_dim = codebook_dim
141
- self.codebook_size = codebook_size
142
-
143
- self.quantizers = nn.ModuleList(
144
- [
145
- VectorQuantize(input_dim, codebook_size, codebook_dim[i], stale_tolerance=stale_tolerance)
146
- for i in range(n_codebooks)
147
- ]
148
- )
149
- self.quantizer_dropout = quantizer_dropout
150
-
151
- def forward(self, z, n_quantizers: int = None):
152
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
153
- the corresponding codebook vectors
154
- Parameters
155
- ----------
156
- z : Tensor[B x D x T]
157
- n_quantizers : int, optional
158
- No. of quantizers to use
159
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
160
- Note: if `self.quantizer_dropout` is True, this argument is ignored
161
- when in training mode, and a random number of quantizers is used.
162
- Returns
163
- -------
164
- dict
165
- A dictionary with the following keys:
166
-
167
- "z" : Tensor[B x D x T]
168
- Quantized continuous representation of input
169
- "codes" : Tensor[B x N x T]
170
- Codebook indices for each codebook
171
- (quantized discrete representation of input)
172
- "latents" : Tensor[B x N*D x T]
173
- Projected latents (continuous representation of input before quantization)
174
- "vq/commitment_loss" : Tensor[1]
175
- Commitment loss to train encoder to predict vectors closer to codebook
176
- entries
177
- "vq/codebook_loss" : Tensor[1]
178
- Codebook loss to update the codebook
179
- """
180
- z_q = 0
181
- residual = z
182
- commitment_loss = 0
183
- codebook_loss = 0
184
-
185
- codebook_indices = []
186
- latents = []
187
-
188
- if n_quantizers is None:
189
- n_quantizers = self.n_codebooks
190
- if self.training:
191
- random_num = random.random()
192
- if random_num<0.6:
193
- n_quantizers = torch.ones((z.shape[0],)) * 1
194
- elif random_num<0.8:
195
- n_quantizers = torch.ones((z.shape[0],)) * 2
196
- else:
197
- n_quantizers = torch.ones((z.shape[0],)) * 4
198
- n_quantizers = n_quantizers.to(z.device)
199
- else:
200
- n_quantizers = torch.ones((z.shape[0],)) * n_quantizers
201
- n_quantizers = n_quantizers.to(z.device)
202
-
203
- for i, quantizer in enumerate(self.quantizers):
204
- # if self.training is False and i >= n_quantizers:
205
- # break
206
-
207
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
208
- residual
209
- )
210
-
211
- # Create mask to apply quantizer dropout
212
- mask = (
213
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
214
- )
215
- z_q = z_q + z_q_i * mask[:, None, None]
216
- residual = residual - z_q_i
217
-
218
- # Sum losses
219
- commitment_loss += (commitment_loss_i * mask).mean()
220
- codebook_loss += (codebook_loss_i * mask).mean()
221
-
222
- codebook_indices.append(indices_i)
223
- latents.append(z_e_i)
224
-
225
- codes = torch.stack(codebook_indices, dim=1)
226
- latents = torch.cat(latents, dim=1)
227
-
228
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
229
- for n in range(encodings.shape[1]):
230
- print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
231
- (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
232
- ))
233
-
234
- return z_q, codes, latents, commitment_loss, codebook_loss, n_quantizers.clamp(max=self.n_codebooks).long() - 1
235
-
236
- def from_codes(self, codes: torch.Tensor):
237
- """Given the quantized codes, reconstruct the continuous representation
238
- Parameters
239
- ----------
240
- codes : Tensor[B x N x T]
241
- Quantized discrete representation of input
242
- Returns
243
- -------
244
- Tensor[B x D x T]
245
- Quantized continuous representation of input
246
- """
247
- z_q = 0.0
248
- z_p = []
249
- n_codebooks = codes.shape[1]
250
- for i in range(n_codebooks):
251
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
252
- z_p.append(z_p_i)
253
-
254
- z_q_i = self.quantizers[i].out_proj(z_p_i)
255
- z_q = z_q + z_q_i
256
- return z_q, torch.cat(z_p, dim=1), codes
257
-
258
- def from_latents(self, latents: torch.Tensor):
259
- """Given the unquantized latents, reconstruct the
260
- continuous representation after quantization.
261
-
262
- Parameters
263
- ----------
264
- latents : Tensor[B x N x T]
265
- Continuous representation of input after projection
266
-
267
- Returns
268
- -------
269
- Tensor[B x D x T]
270
- Quantized representation of full-projected space
271
- Tensor[B x D x T]
272
- Quantized representation of latent space
273
- """
274
- z_q = 0
275
- z_p = []
276
- codes = []
277
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
278
-
279
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
280
- 0
281
- ]
282
- for i in range(n_codebooks):
283
- j, k = dims[i], dims[i + 1]
284
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
285
- z_p.append(z_p_i)
286
- codes.append(codes_i)
287
-
288
- z_q_i = self.quantizers[i].out_proj(z_p_i)
289
- z_q = z_q + z_q_i
290
-
291
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
292
-
293
-
294
- if __name__ == "__main__":
295
- rvq = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 4, codebook_size = 1024, codebook_dim = 32, quantizer_dropout = 0.0)
296
- x = torch.randn(16, 1024, 80)
297
- quantized_prompt_embeds, codes, _, commitment_loss, codebook_loss, rvq_usage = rvq(x)
298
- print(quantized_prompt_embeds.shape)
299
- print(codes.shape)
300
- # w/o reconstruction
301
- loss = commitment_loss * 0.25 + codebook_loss * 1.0
302
- # w/ reconstruction
303
- loss = commitment_loss * 0.25 + codebook_loss * 1.0 + (x - quantized_prompt_embeds).abs().mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_4layer_freezelayer1.py DELETED
@@ -1,301 +0,0 @@
1
- # compared with `descript_quantize2`, we use rvq & random_dropout
2
- from typing import Union
3
-
4
- import numpy as np
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from einops import rearrange
9
- from torch.nn.utils import weight_norm
10
- import random
11
-
12
- def WNConv1d(*args, **kwargs):
13
- return weight_norm(nn.Conv1d(*args, **kwargs))
14
-
15
- class VectorQuantize(nn.Module):
16
- """
17
- Implementation of VQ similar to Karpathy's repo:
18
- https://github.com/karpathy/deep-vector-quantization
19
- Additionally uses following tricks from Improved VQGAN
20
- (https://arxiv.org/pdf/2110.04627.pdf):
21
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
22
- for improved codebook usage
23
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
24
- improves training stability
25
- """
26
-
27
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, stale_tolerance: int = 100):
28
- super().__init__()
29
- self.codebook_size = codebook_size
30
- self.codebook_dim = codebook_dim
31
-
32
- self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
33
- self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
34
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
35
- self.register_buffer("stale_counter", torch.zeros(self.codebook_size,))
36
- self.stale_tolerance = stale_tolerance
37
-
38
- def forward(self, z):
39
- """Quantized the input tensor using a fixed codebook and returns
40
- the corresponding codebook vectors
41
-
42
- Parameters
43
- ----------
44
- z : Tensor[B x D x T]
45
-
46
- Returns
47
- -------
48
- Tensor[B x D x T]
49
- Quantized continuous representation of input
50
- Tensor[1]
51
- Commitment loss to train encoder to predict vectors closer to codebook
52
- entries
53
- Tensor[1]
54
- Codebook loss to update the codebook
55
- Tensor[B x T]
56
- Codebook indices (quantized discrete representation of input)
57
- Tensor[B x D x T]
58
- Projected latents (continuous representation of input before quantization)
59
- """
60
-
61
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
62
- z_e = self.in_proj(z) # z_e : (B x D x T)
63
- z_q, indices = self.decode_latents(z_e)
64
-
65
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
66
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
67
-
68
- z_q = (
69
- z_e + (z_q - z_e).detach()
70
- ) # noop in forward pass, straight-through gradient estimator in backward pass
71
-
72
- z_q = self.out_proj(z_q)
73
-
74
- return z_q, commitment_loss, codebook_loss, indices, z_e
75
-
76
- def embed_code(self, embed_id):
77
- return F.embedding(embed_id, self.codebook.weight)
78
-
79
- def decode_code(self, embed_id):
80
- return self.embed_code(embed_id).transpose(1, 2)
81
-
82
- def decode_latents(self, latents):
83
- encodings = rearrange(latents, "b d t -> (b t) d")
84
- codebook = self.codebook.weight # codebook: (N x D)
85
-
86
- # L2 normalize encodings and codebook (ViT-VQGAN)
87
- encodings = F.normalize(encodings)
88
- codebook = F.normalize(codebook)
89
-
90
- # Compute euclidean distance with codebook
91
- dist = (
92
- encodings.pow(2).sum(1, keepdim=True)
93
- - 2 * encodings @ codebook.t()
94
- + codebook.pow(2).sum(1, keepdim=True).t()
95
- )
96
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
97
- z_q = self.decode_code(indices)
98
-
99
- if(self.training):
100
- onehots = torch.nn.functional.one_hot(indices, self.codebook_size).float() # B, T, codebook_size
101
- stale_codes = (onehots.sum(0).sum(0) == 0).float()
102
- self.stale_counter = self.stale_counter * stale_codes + stale_codes
103
-
104
- # random replace codes that haven't been used for a while
105
- replace_code = (self.stale_counter == self.stale_tolerance).float() # codebook_size
106
- if replace_code.sum(-1) > 0:
107
- print("Replace {} codes".format(replace_code.sum(-1)))
108
- random_input_idx = torch.randperm(encodings.shape[0])
109
- random_input = encodings[random_input_idx].view(encodings.shape)
110
- if random_input.shape[0] < self.codebook_size:
111
- random_input = torch.cat([random_input]*(self.codebook_size // random_input.shape[0] + 1), 0)
112
- random_input = random_input[:self.codebook_size,:].contiguous() # codebook_size, dim
113
-
114
- self.codebook.weight.data = self.codebook.weight.data * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
115
- self.stale_counter = self.stale_counter * (1 - replace_code)
116
-
117
- return z_q, indices
118
-
119
-
120
- class ResidualVectorQuantize(nn.Module):
121
- """
122
- Introduced in SoundStream: An end2end neural audio codec
123
- https://arxiv.org/abs/2107.03312
124
- """
125
-
126
- def __init__(
127
- self,
128
- input_dim: int = 512,
129
- n_codebooks: int = 9,
130
- codebook_size: int = 1024,
131
- codebook_dim: Union[int, list] = 8,
132
- quantizer_dropout: float = 0.0,
133
- stale_tolerance: int = 100,
134
- ):
135
- super().__init__()
136
- if isinstance(codebook_dim, int):
137
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
138
-
139
- self.n_codebooks = n_codebooks
140
- self.codebook_dim = codebook_dim
141
- self.codebook_size = codebook_size
142
-
143
- self.quantizers = nn.ModuleList(
144
- [
145
- VectorQuantize(input_dim, codebook_size, codebook_dim[i], stale_tolerance=stale_tolerance)
146
- for i in range(n_codebooks)
147
- ]
148
- )
149
- self.quantizer_dropout = quantizer_dropout
150
-
151
- def forward(self, z, n_quantizers: int = None):
152
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
153
- the corresponding codebook vectors
154
- Parameters
155
- ----------
156
- z : Tensor[B x D x T]
157
- n_quantizers : int, optional
158
- No. of quantizers to use
159
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
160
- Note: if `self.quantizer_dropout` is True, this argument is ignored
161
- when in training mode, and a random number of quantizers is used.
162
- Returns
163
- -------
164
- dict
165
- A dictionary with the following keys:
166
-
167
- "z" : Tensor[B x D x T]
168
- Quantized continuous representation of input
169
- "codes" : Tensor[B x N x T]
170
- Codebook indices for each codebook
171
- (quantized discrete representation of input)
172
- "latents" : Tensor[B x N*D x T]
173
- Projected latents (continuous representation of input before quantization)
174
- "vq/commitment_loss" : Tensor[1]
175
- Commitment loss to train encoder to predict vectors closer to codebook
176
- entries
177
- "vq/codebook_loss" : Tensor[1]
178
- Codebook loss to update the codebook
179
- """
180
- z_q = 0
181
- residual = z
182
- commitment_loss = 0
183
- codebook_loss = 0
184
-
185
- codebook_indices = []
186
- latents = []
187
-
188
- if n_quantizers is None:
189
- n_quantizers = self.n_codebooks
190
- if self.training:
191
- random_num = random.random()
192
- if random_num<0.6:
193
- n_quantizers = torch.ones((z.shape[0],)) * 2
194
- else:
195
- n_quantizers = torch.ones((z.shape[0],)) * 4
196
- n_quantizers = n_quantizers.to(z.device)
197
- else:
198
- n_quantizers = torch.ones((z.shape[0],)) * n_quantizers
199
- n_quantizers = n_quantizers.to(z.device)
200
-
201
- for i, quantizer in enumerate(self.quantizers):
202
- # if self.training is False and i >= n_quantizers:
203
- # break
204
-
205
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
206
- residual
207
- )
208
-
209
- # Create mask to apply quantizer dropout
210
- mask = (
211
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
212
- )
213
- z_q = z_q + z_q_i * mask[:, None, None]
214
- residual = residual - z_q_i
215
-
216
- # Sum losses
217
- commitment_loss += (commitment_loss_i * mask).mean()
218
- codebook_loss += (codebook_loss_i * mask).mean()
219
-
220
- codebook_indices.append(indices_i)
221
- latents.append(z_e_i)
222
-
223
- codes = torch.stack(codebook_indices, dim=1)
224
- latents = torch.cat(latents, dim=1)
225
-
226
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
227
- # for n in range(encodings.shape[1]):
228
- # print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
229
- # (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
230
- # ))
231
-
232
- return z_q, codes, latents, commitment_loss, codebook_loss, n_quantizers.clamp(max=self.n_codebooks).long() - 1
233
-
234
- def from_codes(self, codes: torch.Tensor):
235
- """Given the quantized codes, reconstruct the continuous representation
236
- Parameters
237
- ----------
238
- codes : Tensor[B x N x T]
239
- Quantized discrete representation of input
240
- Returns
241
- -------
242
- Tensor[B x D x T]
243
- Quantized continuous representation of input
244
- """
245
- z_q = 0.0
246
- z_p = []
247
- n_codebooks = codes.shape[1]
248
- for i in range(n_codebooks):
249
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
250
- z_p.append(z_p_i)
251
-
252
- z_q_i = self.quantizers[i].out_proj(z_p_i)
253
- z_q = z_q + z_q_i
254
- return z_q, torch.cat(z_p, dim=1), codes
255
-
256
- def from_latents(self, latents: torch.Tensor):
257
- """Given the unquantized latents, reconstruct the
258
- continuous representation after quantization.
259
-
260
- Parameters
261
- ----------
262
- latents : Tensor[B x N x T]
263
- Continuous representation of input after projection
264
-
265
- Returns
266
- -------
267
- Tensor[B x D x T]
268
- Quantized representation of full-projected space
269
- Tensor[B x D x T]
270
- Quantized representation of latent space
271
- """
272
- z_q = 0
273
- z_p = []
274
- codes = []
275
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
276
-
277
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
278
- 0
279
- ]
280
- for i in range(n_codebooks):
281
- j, k = dims[i], dims[i + 1]
282
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
283
- z_p.append(z_p_i)
284
- codes.append(codes_i)
285
-
286
- z_q_i = self.quantizers[i].out_proj(z_p_i)
287
- z_q = z_q + z_q_i
288
-
289
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
290
-
291
-
292
- if __name__ == "__main__":
293
- rvq = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 4, codebook_size = 1024, codebook_dim = 32, quantizer_dropout = 0.0)
294
- x = torch.randn(16, 1024, 80)
295
- quantized_prompt_embeds, codes, _, commitment_loss, codebook_loss, rvq_usage = rvq(x)
296
- print(quantized_prompt_embeds.shape)
297
- print(codes.shape)
298
- # w/o reconstruction
299
- loss = commitment_loss * 0.25 + codebook_loss * 1.0
300
- # w/ reconstruction
301
- loss = commitment_loss * 0.25 + codebook_loss * 1.0 + (x - quantized_prompt_embeds).abs().mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_4layer_return_layer.py DELETED
@@ -1,305 +0,0 @@
1
- # compared with `descript_quantize2`, we use rvq & random_dropout
2
- from typing import Union
3
-
4
- import numpy as np
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from einops import rearrange
9
- from torch.nn.utils import weight_norm
10
- import random
11
-
12
- def WNConv1d(*args, **kwargs):
13
- return weight_norm(nn.Conv1d(*args, **kwargs))
14
-
15
- class VectorQuantize(nn.Module):
16
- """
17
- Implementation of VQ similar to Karpathy's repo:
18
- https://github.com/karpathy/deep-vector-quantization
19
- Additionally uses following tricks from Improved VQGAN
20
- (https://arxiv.org/pdf/2110.04627.pdf):
21
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
22
- for improved codebook usage
23
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
24
- improves training stability
25
- """
26
-
27
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, stale_tolerance: int = 100):
28
- super().__init__()
29
- self.codebook_size = codebook_size
30
- self.codebook_dim = codebook_dim
31
-
32
- self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
33
- self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
34
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
35
- self.register_buffer("stale_counter", torch.zeros(self.codebook_size,))
36
- self.stale_tolerance = stale_tolerance
37
-
38
- def forward(self, z):
39
- """Quantized the input tensor using a fixed codebook and returns
40
- the corresponding codebook vectors
41
-
42
- Parameters
43
- ----------
44
- z : Tensor[B x D x T]
45
-
46
- Returns
47
- -------
48
- Tensor[B x D x T]
49
- Quantized continuous representation of input
50
- Tensor[1]
51
- Commitment loss to train encoder to predict vectors closer to codebook
52
- entries
53
- Tensor[1]
54
- Codebook loss to update the codebook
55
- Tensor[B x T]
56
- Codebook indices (quantized discrete representation of input)
57
- Tensor[B x D x T]
58
- Projected latents (continuous representation of input before quantization)
59
- """
60
-
61
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
62
- z_e = self.in_proj(z) # z_e : (B x D x T)
63
- z_q, indices = self.decode_latents(z_e)
64
-
65
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
66
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
67
-
68
- z_q = (
69
- z_e + (z_q - z_e).detach()
70
- ) # noop in forward pass, straight-through gradient estimator in backward pass
71
-
72
- z_q = self.out_proj(z_q)
73
-
74
- return z_q, commitment_loss, codebook_loss, indices, z_e
75
-
76
- def embed_code(self, embed_id):
77
- return F.embedding(embed_id, self.codebook.weight)
78
-
79
- def decode_code(self, embed_id):
80
- return self.embed_code(embed_id).transpose(1, 2)
81
-
82
- def decode_latents(self, latents):
83
- encodings = rearrange(latents, "b d t -> (b t) d")
84
- codebook = self.codebook.weight # codebook: (N x D)
85
-
86
- # L2 normalize encodings and codebook (ViT-VQGAN)
87
- encodings = F.normalize(encodings)
88
- codebook = F.normalize(codebook)
89
-
90
- # Compute euclidean distance with codebook
91
- dist = (
92
- encodings.pow(2).sum(1, keepdim=True)
93
- - 2 * encodings @ codebook.t()
94
- + codebook.pow(2).sum(1, keepdim=True).t()
95
- )
96
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
97
- z_q = self.decode_code(indices)
98
-
99
- if(self.training):
100
- onehots = torch.nn.functional.one_hot(indices, self.codebook_size).float() # B, T, codebook_size
101
- stale_codes = (onehots.sum(0).sum(0) == 0).float()
102
- self.stale_counter = self.stale_counter * stale_codes + stale_codes
103
-
104
- # random replace codes that haven't been used for a while
105
- replace_code = (self.stale_counter == self.stale_tolerance).float() # codebook_size
106
- if replace_code.sum(-1) > 0:
107
- print("Replace {} codes".format(replace_code.sum(-1)))
108
- random_input_idx = torch.randperm(encodings.shape[0])
109
- random_input = encodings[random_input_idx].view(encodings.shape)
110
- if random_input.shape[0] < self.codebook_size:
111
- random_input = torch.cat([random_input]*(self.codebook_size // random_input.shape[0] + 1), 0)
112
- random_input = random_input[:self.codebook_size,:].contiguous() # codebook_size, dim
113
-
114
- self.codebook.weight.data = self.codebook.weight.data * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
115
- self.stale_counter = self.stale_counter * (1 - replace_code)
116
-
117
- return z_q, indices
118
-
119
-
120
- class ResidualVectorQuantize(nn.Module):
121
- """
122
- Introduced in SoundStream: An end2end neural audio codec
123
- https://arxiv.org/abs/2107.03312
124
- """
125
-
126
- def __init__(
127
- self,
128
- input_dim: int = 512,
129
- n_codebooks: int = 9,
130
- codebook_size: int = 1024,
131
- codebook_dim: Union[int, list] = 8,
132
- quantizer_dropout: float = 0.0,
133
- stale_tolerance: int = 100,
134
- ):
135
- super().__init__()
136
- if isinstance(codebook_dim, int):
137
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
138
-
139
- self.n_codebooks = n_codebooks
140
- self.codebook_dim = codebook_dim
141
- self.codebook_size = codebook_size
142
-
143
- self.quantizers = nn.ModuleList(
144
- [
145
- VectorQuantize(input_dim, codebook_size, codebook_dim[i], stale_tolerance=stale_tolerance)
146
- for i in range(n_codebooks)
147
- ]
148
- )
149
- self.quantizer_dropout = quantizer_dropout
150
-
151
- def forward(self, z, n_quantizers: int = None):
152
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
153
- the corresponding codebook vectors
154
- Parameters
155
- ----------
156
- z : Tensor[B x D x T]
157
- n_quantizers : int, optional
158
- No. of quantizers to use
159
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
160
- Note: if `self.quantizer_dropout` is True, this argument is ignored
161
- when in training mode, and a random number of quantizers is used.
162
- Returns
163
- -------
164
- dict
165
- A dictionary with the following keys:
166
-
167
- "z" : Tensor[B x D x T]
168
- Quantized continuous representation of input
169
- "codes" : Tensor[B x N x T]
170
- Codebook indices for each codebook
171
- (quantized discrete representation of input)
172
- "latents" : Tensor[B x N*D x T]
173
- Projected latents (continuous representation of input before quantization)
174
- "vq/commitment_loss" : Tensor[1]
175
- Commitment loss to train encoder to predict vectors closer to codebook
176
- entries
177
- "vq/codebook_loss" : Tensor[1]
178
- Codebook loss to update the codebook
179
- """
180
- z_q = 0
181
- residual = z
182
- commitment_loss = 0
183
- codebook_loss = 0
184
- layer = self.n_codebooks
185
- codebook_indices = []
186
- latents = []
187
-
188
- if n_quantizers is None:
189
- n_quantizers = self.n_codebooks
190
- if self.training:
191
- random_num = random.random()
192
- if random_num<0.6:
193
- n_quantizers = torch.ones((z.shape[0],)) * 1
194
- elif random_num<0.8:
195
- n_quantizers = torch.ones((z.shape[0],)) * 2
196
- layer = 2
197
- else:
198
- n_quantizers = torch.ones((z.shape[0],)) * 4
199
- layer = 4
200
- n_quantizers = n_quantizers.to(z.device)
201
- else:
202
- n_quantizers = torch.ones((z.shape[0],)) * n_quantizers
203
- n_quantizers = n_quantizers.to(z.device)
204
-
205
- for i, quantizer in enumerate(self.quantizers):
206
- # if self.training is False and i >= n_quantizers:
207
- # break
208
-
209
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
210
- residual
211
- )
212
-
213
- # Create mask to apply quantizer dropout
214
- mask = (
215
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
216
- )
217
- z_q = z_q + z_q_i * mask[:, None, None]
218
- residual = residual - z_q_i
219
-
220
- # Sum losses
221
- commitment_loss += (commitment_loss_i * mask).mean()
222
- codebook_loss += (codebook_loss_i * mask).mean()
223
-
224
- codebook_indices.append(indices_i)
225
- latents.append(z_e_i)
226
-
227
- codes = torch.stack(codebook_indices, dim=1)
228
- latents = torch.cat(latents, dim=1)
229
-
230
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
231
- for n in range(encodings.shape[1]):
232
- print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
233
- (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
234
- ))
235
-
236
- return z_q, codes, latents, commitment_loss, codebook_loss, n_quantizers.clamp(max=self.n_codebooks).long() - 1,layer
237
-
238
- def from_codes(self, codes: torch.Tensor):
239
- """Given the quantized codes, reconstruct the continuous representation
240
- Parameters
241
- ----------
242
- codes : Tensor[B x N x T]
243
- Quantized discrete representation of input
244
- Returns
245
- -------
246
- Tensor[B x D x T]
247
- Quantized continuous representation of input
248
- """
249
- z_q = 0.0
250
- z_p = []
251
- n_codebooks = codes.shape[1]
252
- for i in range(n_codebooks):
253
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
254
- z_p.append(z_p_i)
255
-
256
- z_q_i = self.quantizers[i].out_proj(z_p_i)
257
- z_q = z_q + z_q_i
258
- return z_q, torch.cat(z_p, dim=1), codes
259
-
260
- def from_latents(self, latents: torch.Tensor):
261
- """Given the unquantized latents, reconstruct the
262
- continuous representation after quantization.
263
-
264
- Parameters
265
- ----------
266
- latents : Tensor[B x N x T]
267
- Continuous representation of input after projection
268
-
269
- Returns
270
- -------
271
- Tensor[B x D x T]
272
- Quantized representation of full-projected space
273
- Tensor[B x D x T]
274
- Quantized representation of latent space
275
- """
276
- z_q = 0
277
- z_p = []
278
- codes = []
279
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
280
-
281
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
282
- 0
283
- ]
284
- for i in range(n_codebooks):
285
- j, k = dims[i], dims[i + 1]
286
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
287
- z_p.append(z_p_i)
288
- codes.append(codes_i)
289
-
290
- z_q_i = self.quantizers[i].out_proj(z_p_i)
291
- z_q = z_q + z_q_i
292
-
293
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
294
-
295
-
296
- if __name__ == "__main__":
297
- rvq = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 4, codebook_size = 1024, codebook_dim = 32, quantizer_dropout = 0.0)
298
- x = torch.randn(16, 1024, 80)
299
- quantized_prompt_embeds, codes, _, commitment_loss, codebook_loss, rvq_usage = rvq(x)
300
- print(quantized_prompt_embeds.shape)
301
- print(codes.shape)
302
- # w/o reconstruction
303
- loss = commitment_loss * 0.25 + codebook_loss * 1.0
304
- # w/ reconstruction
305
- loss = commitment_loss * 0.25 + codebook_loss * 1.0 + (x - quantized_prompt_embeds).abs().mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_4layer_test.py DELETED
@@ -1,307 +0,0 @@
1
- # compared with `descript_quantize2`, we use rvq & random_dropout
2
- from typing import Union
3
-
4
- import numpy as np
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from einops import rearrange
9
- from torch.nn.utils import weight_norm
10
- import random
11
-
12
- def WNConv1d(*args, **kwargs):
13
- return weight_norm(nn.Conv1d(*args, **kwargs))
14
-
15
- class VectorQuantize(nn.Module):
16
- """
17
- Implementation of VQ similar to Karpathy's repo:
18
- https://github.com/karpathy/deep-vector-quantization
19
- Additionally uses following tricks from Improved VQGAN
20
- (https://arxiv.org/pdf/2110.04627.pdf):
21
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
22
- for improved codebook usage
23
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
24
- improves training stability
25
- """
26
-
27
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, stale_tolerance: int = 100):
28
- super().__init__()
29
- self.codebook_size = codebook_size
30
- self.codebook_dim = codebook_dim
31
-
32
- self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
33
- self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
34
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
35
- self.register_buffer("stale_counter", torch.zeros(self.codebook_size,))
36
- self.stale_tolerance = stale_tolerance
37
-
38
- def forward(self, z):
39
- """Quantized the input tensor using a fixed codebook and returns
40
- the corresponding codebook vectors
41
-
42
- Parameters
43
- ----------
44
- z : Tensor[B x D x T]
45
-
46
- Returns
47
- -------
48
- Tensor[B x D x T]
49
- Quantized continuous representation of input
50
- Tensor[1]
51
- Commitment loss to train encoder to predict vectors closer to codebook
52
- entries
53
- Tensor[1]
54
- Codebook loss to update the codebook
55
- Tensor[B x T]
56
- Codebook indices (quantized discrete representation of input)
57
- Tensor[B x D x T]
58
- Projected latents (continuous representation of input before quantization)
59
- """
60
-
61
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
62
- z_e = self.in_proj(z) # z_e : (B x D x T)
63
- z_q, indices = self.decode_latents(z_e)
64
-
65
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
66
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
67
-
68
- z_q = (
69
- z_e + (z_q - z_e).detach()
70
- ) # noop in forward pass, straight-through gradient estimator in backward pass
71
-
72
- z_q = self.out_proj(z_q)
73
-
74
- return z_q, commitment_loss, codebook_loss, indices, z_e
75
-
76
- def embed_code(self, embed_id):
77
- return F.embedding(embed_id, self.codebook.weight)
78
-
79
- def decode_code(self, embed_id):
80
- return self.embed_code(embed_id).transpose(1, 2)
81
-
82
- def decode_latents(self, latents):
83
- encodings = rearrange(latents, "b d t -> (b t) d")
84
- codebook = self.codebook.weight # codebook: (N x D)
85
-
86
- # L2 normalize encodings and codebook (ViT-VQGAN)
87
- encodings = F.normalize(encodings)
88
- codebook = F.normalize(codebook)
89
-
90
- # Compute euclidean distance with codebook
91
- dist = (
92
- encodings.pow(2).sum(1, keepdim=True)
93
- - 2 * encodings @ codebook.t()
94
- + codebook.pow(2).sum(1, keepdim=True).t()
95
- )
96
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
97
- z_q = self.decode_code(indices)
98
-
99
- if(self.training):
100
- onehots = torch.nn.functional.one_hot(indices, self.codebook_size).float() # B, T, codebook_size
101
- stale_codes = (onehots.sum(0).sum(0) == 0).float()
102
- self.stale_counter = self.stale_counter * stale_codes + stale_codes
103
-
104
- # random replace codes that haven't been used for a while
105
- replace_code = (self.stale_counter == self.stale_tolerance).float() # codebook_size
106
- if replace_code.sum(-1) > 0:
107
- print("Replace {} codes".format(replace_code.sum(-1)))
108
- random_input_idx = torch.randperm(encodings.shape[0])
109
- random_input = encodings[random_input_idx].view(encodings.shape)
110
- if random_input.shape[0] < self.codebook_size:
111
- random_input = torch.cat([random_input]*(self.codebook_size // random_input.shape[0] + 1), 0)
112
- random_input = random_input[:self.codebook_size,:].contiguous() # codebook_size, dim
113
-
114
- self.codebook.weight.data = self.codebook.weight.data * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
115
- self.stale_counter = self.stale_counter * (1 - replace_code)
116
-
117
- return z_q, indices
118
-
119
-
120
- class ResidualVectorQuantize(nn.Module):
121
- """
122
- Introduced in SoundStream: An end2end neural audio codec
123
- https://arxiv.org/abs/2107.03312
124
- """
125
-
126
- def __init__(
127
- self,
128
- input_dim: int = 512,
129
- n_codebooks: int = 9,
130
- codebook_size: int = 1024,
131
- codebook_dim: Union[int, list] = 8,
132
- quantizer_dropout: float = 0.0,
133
- stale_tolerance: int = 100,
134
- ):
135
- super().__init__()
136
- if isinstance(codebook_dim, int):
137
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
138
-
139
- self.n_codebooks = n_codebooks
140
- self.codebook_dim = codebook_dim
141
- self.codebook_size = codebook_size
142
-
143
- self.quantizers = nn.ModuleList(
144
- [
145
- VectorQuantize(input_dim, codebook_size, codebook_dim[i], stale_tolerance=stale_tolerance)
146
- for i in range(n_codebooks)
147
- ]
148
- )
149
- self.quantizer_dropout = quantizer_dropout
150
-
151
- def forward(self, z, n_quantizers: int = None):
152
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
153
- the corresponding codebook vectors
154
- Parameters
155
- ----------
156
- z : Tensor[B x D x T]
157
- n_quantizers : int, optional
158
- No. of quantizers to use
159
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
160
- Note: if `self.quantizer_dropout` is True, this argument is ignored
161
- when in training mode, and a random number of quantizers is used.
162
- Returns
163
- -------
164
- dict
165
- A dictionary with the following keys:
166
-
167
- "z" : Tensor[B x D x T]
168
- Quantized continuous representation of input
169
- "codes" : Tensor[B x N x T]
170
- Codebook indices for each codebook
171
- (quantized discrete representation of input)
172
- "latents" : Tensor[B x N*D x T]
173
- Projected latents (continuous representation of input before quantization)
174
- "vq/commitment_loss" : Tensor[1]
175
- Commitment loss to train encoder to predict vectors closer to codebook
176
- entries
177
- "vq/codebook_loss" : Tensor[1]
178
- Codebook loss to update the codebook
179
- """
180
- z_q = 0
181
- residual = z
182
- commitment_loss = 0
183
- codebook_loss = 0
184
-
185
- codebook_indices = []
186
- latents = []
187
-
188
- if n_quantizers is None:
189
- n_quantizers = self.n_codebooks
190
- if self.training:
191
- random_num = random.random()
192
- # random_num = 1.0
193
- print("Random number: {:.2f}".format(random_num))
194
- if random_num<0.6:
195
- n_quantizers = torch.ones((z.shape[0],)) * 1
196
- elif random_num<0.8:
197
- n_quantizers = torch.ones((z.shape[0],)) * 2
198
- else:
199
- n_quantizers = torch.ones((z.shape[0],)) * 4
200
- n_quantizers = n_quantizers.to(z.device)
201
- else:
202
- n_quantizers = torch.ones((z.shape[0],)) * n_quantizers
203
- n_quantizers = n_quantizers.to(z.device)
204
- print("Number of quantizers: ", n_quantizers)
205
-
206
- for i, quantizer in enumerate(self.quantizers):
207
- # if self.training is False and i >= n_quantizers:
208
- # break
209
-
210
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
211
- residual
212
- )
213
-
214
- # Create mask to apply quantizer dropout
215
- mask = (
216
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
217
- )
218
- print("mask: ", mask)
219
- z_q = z_q + z_q_i * mask[:, None, None]
220
- residual = residual - z_q_i
221
-
222
- # Sum losses
223
- commitment_loss += (commitment_loss_i * mask).mean()
224
- codebook_loss += (codebook_loss_i * mask).mean()
225
-
226
- codebook_indices.append(indices_i)
227
- latents.append(z_e_i)
228
-
229
- codes = torch.stack(codebook_indices, dim=1)
230
- latents = torch.cat(latents, dim=1)
231
-
232
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
233
- for n in range(encodings.shape[1]):
234
- print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
235
- (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
236
- ))
237
-
238
- return z_q, codes, latents, commitment_loss, codebook_loss, n_quantizers.clamp(max=self.n_codebooks).long() - 1
239
-
240
- def from_codes(self, codes: torch.Tensor):
241
- """Given the quantized codes, reconstruct the continuous representation
242
- Parameters
243
- ----------
244
- codes : Tensor[B x N x T]
245
- Quantized discrete representation of input
246
- Returns
247
- -------
248
- Tensor[B x D x T]
249
- Quantized continuous representation of input
250
- """
251
- z_q = 0.0
252
- z_p = []
253
- n_codebooks = codes.shape[1]
254
- for i in range(n_codebooks):
255
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
256
- z_p.append(z_p_i)
257
-
258
- z_q_i = self.quantizers[i].out_proj(z_p_i)
259
- z_q = z_q + z_q_i
260
- return z_q, torch.cat(z_p, dim=1), codes
261
-
262
- def from_latents(self, latents: torch.Tensor):
263
- """Given the unquantized latents, reconstruct the
264
- continuous representation after quantization.
265
-
266
- Parameters
267
- ----------
268
- latents : Tensor[B x N x T]
269
- Continuous representation of input after projection
270
-
271
- Returns
272
- -------
273
- Tensor[B x D x T]
274
- Quantized representation of full-projected space
275
- Tensor[B x D x T]
276
- Quantized representation of latent space
277
- """
278
- z_q = 0
279
- z_p = []
280
- codes = []
281
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
282
-
283
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
284
- 0
285
- ]
286
- for i in range(n_codebooks):
287
- j, k = dims[i], dims[i + 1]
288
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
289
- z_p.append(z_p_i)
290
- codes.append(codes_i)
291
-
292
- z_q_i = self.quantizers[i].out_proj(z_p_i)
293
- z_q = z_q + z_q_i
294
-
295
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
296
-
297
-
298
- if __name__ == "__main__":
299
- rvq = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 4, codebook_size = 1024, codebook_dim = 32, quantizer_dropout = 0.0)
300
- x = torch.randn(16, 1024, 80)
301
- quantized_prompt_embeds, codes, _, commitment_loss, codebook_loss, rvq_usage = rvq(x)
302
- print(quantized_prompt_embeds.shape)
303
- print(codes.shape)
304
- # w/o reconstruction
305
- loss = commitment_loss * 0.25 + codebook_loss * 1.0
306
- # w/ reconstruction
307
- loss = commitment_loss * 0.25 + codebook_loss * 1.0 + (x - quantized_prompt_embeds).abs().mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_nodown.py DELETED
@@ -1,300 +0,0 @@
1
- # compared with `descript_quantize2`, we use rvq & random_dropout
2
- from typing import Union
3
-
4
- import numpy as np
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from einops import rearrange
9
- from torch.nn.utils import weight_norm
10
-
11
- def WNConv1d(*args, **kwargs):
12
- return weight_norm(nn.Conv1d(*args, **kwargs))
13
-
14
- class VectorQuantize(nn.Module):
15
- """
16
- Implementation of VQ similar to Karpathy's repo:
17
- https://github.com/karpathy/deep-vector-quantization
18
- Additionally uses following tricks from Improved VQGAN
19
- (https://arxiv.org/pdf/2110.04627.pdf):
20
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
21
- for improved codebook usage
22
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
23
- improves training stability
24
- """
25
-
26
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, stale_tolerance: int = 100):
27
- super().__init__()
28
- self.codebook_size = codebook_size
29
- self.codebook_dim = codebook_dim
30
-
31
- # self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
32
- self.in_proj = nn.Identity()
33
- self.out_proj = nn.Identity()
34
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
35
- self.register_buffer("stale_counter", torch.zeros(self.codebook_size,))
36
- self.stale_tolerance = stale_tolerance
37
-
38
- def forward(self, z):
39
- """Quantized the input tensor using a fixed codebook and returns
40
- the corresponding codebook vectors
41
-
42
- Parameters
43
- ----------
44
- z : Tensor[B x D x T]
45
-
46
- Returns
47
- -------
48
- Tensor[B x D x T]
49
- Quantized continuous representation of input
50
- Tensor[1]
51
- Commitment loss to train encoder to predict vectors closer to codebook
52
- entries
53
- Tensor[1]
54
- Codebook loss to update the codebook
55
- Tensor[B x T]
56
- Codebook indices (quantized discrete representation of input)
57
- Tensor[B x D x T]
58
- Projected latents (continuous representation of input before quantization)
59
- """
60
-
61
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
62
- z_e = self.in_proj(z) # z_e : (B x D x T)
63
- z_q, indices = self.decode_latents(z_e)
64
-
65
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
66
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
67
-
68
- z_q = (
69
- z_e + (z_q - z_e).detach()
70
- ) # noop in forward pass, straight-through gradient estimator in backward pass
71
-
72
- z_q = self.out_proj(z_q)
73
-
74
- return z_q, commitment_loss, codebook_loss, indices, z_e
75
-
76
- def embed_code(self, embed_id):
77
- return F.embedding(embed_id, self.codebook.weight)
78
-
79
- def decode_code(self, embed_id):
80
- return self.embed_code(embed_id).transpose(1, 2)
81
-
82
- def decode_latents(self, latents):
83
- encodings = rearrange(latents, "b d t -> (b t) d")
84
- codebook = self.codebook.weight # codebook: (N x D)
85
-
86
- # L2 normalize encodings and codebook (ViT-VQGAN)
87
- encodings = F.normalize(encodings)
88
- codebook = F.normalize(codebook)
89
-
90
- # Compute euclidean distance with codebook
91
- dist = (
92
- encodings.pow(2).sum(1, keepdim=True)
93
- - 2 * encodings @ codebook.t()
94
- + codebook.pow(2).sum(1, keepdim=True).t()
95
- )
96
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
97
- z_q = self.decode_code(indices)
98
-
99
- if(self.training):
100
- onehots = torch.nn.functional.one_hot(indices, self.codebook_size).float() # B, T, codebook_size
101
- stale_codes = (onehots.sum(0).sum(0) == 0).float()
102
- self.stale_counter = self.stale_counter * stale_codes + stale_codes
103
-
104
- # random replace codes that haven't been used for a while
105
- replace_code = (self.stale_counter == self.stale_tolerance).float() # codebook_size
106
- if replace_code.sum(-1) > 0:
107
- print("Replace {} codes".format(replace_code.sum(-1)))
108
- random_input_idx = torch.randperm(encodings.shape[0])
109
- random_input = encodings[random_input_idx].view(encodings.shape)
110
- if random_input.shape[0] < self.codebook_size:
111
- random_input = torch.cat([random_input]*(self.codebook_size // random_input.shape[0] + 1), 0)
112
- random_input = random_input[:self.codebook_size,:].contiguous() # codebook_size, dim
113
-
114
- self.codebook.weight.data = self.codebook.weight.data * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
115
- self.stale_counter = self.stale_counter * (1 - replace_code)
116
-
117
- return z_q, indices
118
-
119
-
120
- class ResidualVectorQuantize(nn.Module):
121
- """
122
- Introduced in SoundStream: An end2end neural audio codec
123
- https://arxiv.org/abs/2107.03312
124
- """
125
-
126
- def __init__(
127
- self,
128
- input_dim: int = 512,
129
- n_codebooks: int = 9,
130
- codebook_size: int = 1024,
131
- codebook_dim: Union[int, list] = 8,
132
- quantizer_dropout: float = 0.0,
133
- stale_tolerance: int = 100,
134
- ):
135
- super().__init__()
136
- if isinstance(codebook_dim, int):
137
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
138
-
139
- self.n_codebooks = n_codebooks
140
- self.codebook_dim = codebook_dim
141
- self.codebook_size = codebook_size
142
-
143
- self.quantizers = nn.ModuleList(
144
- [
145
- VectorQuantize(input_dim, codebook_size, codebook_dim[i], stale_tolerance=stale_tolerance)
146
- for i in range(n_codebooks)
147
- ]
148
- )
149
- self.quantizer_dropout = quantizer_dropout
150
-
151
- def forward(self, z, n_quantizers: int = None):
152
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
153
- the corresponding codebook vectors
154
- Parameters
155
- ----------
156
- z : Tensor[B x D x T]
157
- n_quantizers : int, optional
158
- No. of quantizers to use
159
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
160
- Note: if `self.quantizer_dropout` is True, this argument is ignored
161
- when in training mode, and a random number of quantizers is used.
162
- Returns
163
- -------
164
- dict
165
- A dictionary with the following keys:
166
-
167
- "z" : Tensor[B x D x T]
168
- Quantized continuous representation of input
169
- "codes" : Tensor[B x N x T]
170
- Codebook indices for each codebook
171
- (quantized discrete representation of input)
172
- "latents" : Tensor[B x N*D x T]
173
- Projected latents (continuous representation of input before quantization)
174
- "vq/commitment_loss" : Tensor[1]
175
- Commitment loss to train encoder to predict vectors closer to codebook
176
- entries
177
- "vq/codebook_loss" : Tensor[1]
178
- Codebook loss to update the codebook
179
- """
180
- z_q = 0
181
- residual = z
182
- commitment_loss = 0
183
- codebook_loss = 0
184
-
185
- codebook_indices = []
186
- latents = []
187
-
188
- if n_quantizers is None:
189
- n_quantizers = self.n_codebooks
190
- if self.training:
191
- n_quantizers = torch.ones((z.shape[0],)) * self.n_codebooks + 1
192
- dropout = torch.randint(1, self.n_codebooks + 1, (z.shape[0],))
193
- n_dropout = int(z.shape[0] * self.quantizer_dropout)
194
- n_quantizers[:n_dropout] = dropout[:n_dropout]
195
- n_quantizers = n_quantizers.to(z.device)
196
- else:
197
- n_quantizers = torch.ones((z.shape[0],)) * n_quantizers + 1
198
- n_quantizers = n_quantizers.to(z.device)
199
-
200
- for i, quantizer in enumerate(self.quantizers):
201
- # if self.training is False and i >= n_quantizers:
202
- # break
203
-
204
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
205
- residual
206
- )
207
-
208
- # Create mask to apply quantizer dropout
209
- mask = (
210
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
211
- )
212
- z_q = z_q + z_q_i * mask[:, None, None]
213
- residual = residual - z_q_i
214
-
215
- # Sum losses
216
- commitment_loss += (commitment_loss_i * mask).mean()
217
- codebook_loss += (codebook_loss_i * mask).mean()
218
-
219
- codebook_indices.append(indices_i)
220
- latents.append(z_e_i)
221
-
222
- codes = torch.stack(codebook_indices, dim=1)
223
- latents = torch.cat(latents, dim=1)
224
-
225
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
226
- for n in range(encodings.shape[1]):
227
- print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
228
- (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
229
- ))
230
-
231
- return z_q, codes, latents, commitment_loss, codebook_loss, n_quantizers.clamp(max=self.n_codebooks).long() - 1
232
-
233
- def from_codes(self, codes: torch.Tensor):
234
- """Given the quantized codes, reconstruct the continuous representation
235
- Parameters
236
- ----------
237
- codes : Tensor[B x N x T]
238
- Quantized discrete representation of input
239
- Returns
240
- -------
241
- Tensor[B x D x T]
242
- Quantized continuous representation of input
243
- """
244
- z_q = 0.0
245
- z_p = []
246
- n_codebooks = codes.shape[1]
247
- for i in range(n_codebooks):
248
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
249
- z_p.append(z_p_i)
250
-
251
- z_q_i = self.quantizers[i].out_proj(z_p_i)
252
- z_q = z_q + z_q_i
253
- return z_q, torch.cat(z_p, dim=1), codes
254
-
255
- def from_latents(self, latents: torch.Tensor):
256
- """Given the unquantized latents, reconstruct the
257
- continuous representation after quantization.
258
-
259
- Parameters
260
- ----------
261
- latents : Tensor[B x N x T]
262
- Continuous representation of input after projection
263
-
264
- Returns
265
- -------
266
- Tensor[B x D x T]
267
- Quantized representation of full-projected space
268
- Tensor[B x D x T]
269
- Quantized representation of latent space
270
- """
271
- z_q = 0
272
- z_p = []
273
- codes = []
274
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
275
-
276
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
277
- 0
278
- ]
279
- for i in range(n_codebooks):
280
- j, k = dims[i], dims[i + 1]
281
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
282
- z_p.append(z_p_i)
283
- codes.append(codes_i)
284
-
285
- z_q_i = self.quantizers[i].out_proj(z_p_i)
286
- z_q = z_q + z_q_i
287
-
288
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
289
-
290
-
291
- if __name__ == "__main__":
292
- rvq = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 4, codebook_size = 1024, codebook_dim = 32, quantizer_dropout = 0.0)
293
- x = torch.randn(16, 1024, 80)
294
- quantized_prompt_embeds, codes, _, commitment_loss, codebook_loss, rvq_usage = rvq(x)
295
- print(quantized_prompt_embeds.shape)
296
- print(codes.shape)
297
- # w/o reconstruction
298
- loss = commitment_loss * 0.25 + codebook_loss * 1.0
299
- # w/ reconstruction
300
- loss = commitment_loss * 0.25 + codebook_loss * 1.0 + (x - quantized_prompt_embeds).abs().mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_randomdrop.py DELETED
@@ -1,321 +0,0 @@
1
- # compared with `descript_quantize2`, we use rvq & random_dropout
2
- from typing import Union
3
-
4
- import numpy as np
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from einops import rearrange
9
- from torch.nn.utils import weight_norm
10
-
11
- def WNConv1d(*args, **kwargs):
12
- return weight_norm(nn.Conv1d(*args, **kwargs))
13
-
14
- class VectorQuantize(nn.Module):
15
- """
16
- Implementation of VQ similar to Karpathy's repo:
17
- https://github.com/karpathy/deep-vector-quantization
18
- Additionally uses following tricks from Improved VQGAN
19
- (https://arxiv.org/pdf/2110.04627.pdf):
20
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
21
- for improved codebook usage
22
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
23
- improves training stability
24
- """
25
-
26
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, stale_tolerance: int = 100):
27
- super().__init__()
28
- self.codebook_size = codebook_size
29
- self.codebook_dim = codebook_dim
30
-
31
- self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
32
- self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
33
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
34
- self.register_buffer("stale_counter", torch.zeros(self.codebook_size,))
35
- self.stale_tolerance = stale_tolerance
36
-
37
- def forward(self, z):
38
- """Quantized the input tensor using a fixed codebook and returns
39
- the corresponding codebook vectors
40
-
41
- Parameters
42
- ----------
43
- z : Tensor[B x D x T]
44
-
45
- Returns
46
- -------
47
- Tensor[B x D x T]
48
- Quantized continuous representation of input
49
- Tensor[1]
50
- Commitment loss to train encoder to predict vectors closer to codebook
51
- entries
52
- Tensor[1]
53
- Codebook loss to update the codebook
54
- Tensor[B x T]
55
- Codebook indices (quantized discrete representation of input)
56
- Tensor[B x D x T]
57
- Projected latents (continuous representation of input before quantization)
58
- """
59
-
60
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
61
- z_e = self.in_proj(z) # z_e : (B x D x T)
62
- z_q, indices = self.decode_latents(z_e)
63
-
64
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
65
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
66
-
67
- z_q = (
68
- z_e + (z_q - z_e).detach()
69
- ) # noop in forward pass, straight-through gradient estimator in backward pass
70
-
71
- z_q = self.out_proj(z_q)
72
-
73
- return z_q, commitment_loss, codebook_loss, indices, z_e
74
-
75
- def embed_code(self, embed_id):
76
- return F.embedding(embed_id, self.codebook.weight)
77
-
78
- def decode_code(self, embed_id):
79
- return self.embed_code(embed_id).transpose(1, 2)
80
-
81
- def dropout_code(self,code,dropout_rate=0.05):
82
- total_elements = code.shape[0] * code.shape[1]
83
- dropout_elements = int(total_elements * dropout_rate)
84
- dropout_indices = np.random.choice(np.arange(total_elements), size=dropout_elements, replace=False)
85
- # 对每个选择的元素位置进行替换
86
- for idx in dropout_indices:
87
- # 计算二维索引
88
- i = idx // code.shape[1]
89
- j = idx % code.shape[1]
90
- # 替换元素
91
- code[i, j] = np.random.randint(0, self.codebook_size)
92
- return code
93
-
94
- def decode_latents(self, latents):
95
- encodings = rearrange(latents, "b d t -> (b t) d")
96
- codebook = self.codebook.weight # codebook: (N x D)
97
-
98
- # L2 normalize encodings and codebook (ViT-VQGAN)
99
- encodings = F.normalize(encodings)
100
- codebook = F.normalize(codebook)
101
-
102
- # Compute euclidean distance with codebook
103
- dist = (
104
- encodings.pow(2).sum(1, keepdim=True)
105
- - 2 * encodings @ codebook.t()
106
- + codebook.pow(2).sum(1, keepdim=True).t()
107
- )
108
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
109
- if self.training:
110
- print("train")
111
- indices = self.dropout_code(indices, dropout_rate=0.1)
112
-
113
- # print("indices", indices.shape)
114
- #random replace 10% indices
115
- # if(self.training):
116
-
117
- z_q = self.decode_code(indices)
118
-
119
- if(self.training):
120
- onehots = torch.nn.functional.one_hot(indices, self.codebook_size).float() # B, T, codebook_size
121
- stale_codes = (onehots.sum(0).sum(0) == 0).float()
122
- self.stale_counter = self.stale_counter * stale_codes + stale_codes
123
-
124
- # random replace codes that haven't been used for a while
125
- replace_code = (self.stale_counter == self.stale_tolerance).float() # codebook_size
126
- if replace_code.sum(-1) > 0:
127
- print("Replace {} codes".format(replace_code.sum(-1)))
128
- random_input_idx = torch.randperm(encodings.shape[0])
129
- random_input = encodings[random_input_idx].view(encodings.shape)
130
- if random_input.shape[0] < self.codebook_size:
131
- random_input = torch.cat([random_input]*(self.codebook_size // random_input.shape[0] + 1), 0)
132
- random_input = random_input[:self.codebook_size,:].contiguous() # codebook_size, dim
133
-
134
- self.codebook.weight.data = self.codebook.weight.data * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
135
- self.stale_counter = self.stale_counter * (1 - replace_code)
136
-
137
- return z_q, indices
138
-
139
-
140
- class ResidualVectorQuantize(nn.Module):
141
- """
142
- Introduced in SoundStream: An end2end neural audio codec
143
- https://arxiv.org/abs/2107.03312
144
- """
145
-
146
- def __init__(
147
- self,
148
- input_dim: int = 512,
149
- n_codebooks: int = 9,
150
- codebook_size: int = 1024,
151
- codebook_dim: Union[int, list] = 8,
152
- quantizer_dropout: float = 0.0,
153
- stale_tolerance: int = 100,
154
- ):
155
- super().__init__()
156
- if isinstance(codebook_dim, int):
157
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
158
-
159
- self.n_codebooks = n_codebooks
160
- self.codebook_dim = codebook_dim
161
- self.codebook_size = codebook_size
162
-
163
- self.quantizers = nn.ModuleList(
164
- [
165
- VectorQuantize(input_dim, codebook_size, codebook_dim[i], stale_tolerance=stale_tolerance)
166
- for i in range(n_codebooks)
167
- ]
168
- )
169
- self.quantizer_dropout = quantizer_dropout
170
-
171
- def forward(self, z, n_quantizers: int = None):
172
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
173
- the corresponding codebook vectors
174
- Parameters
175
- ----------
176
- z : Tensor[B x D x T]
177
- n_quantizers : int, optional
178
- No. of quantizers to use
179
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
180
- Note: if `self.quantizer_dropout` is True, this argument is ignored
181
- when in training mode, and a random number of quantizers is used.
182
- Returns
183
- -------
184
- dict
185
- A dictionary with the following keys:
186
-
187
- "z" : Tensor[B x D x T]
188
- Quantized continuous representation of input
189
- "codes" : Tensor[B x N x T]
190
- Codebook indices for each codebook
191
- (quantized discrete representation of input)
192
- "latents" : Tensor[B x N*D x T]
193
- Projected latents (continuous representation of input before quantization)
194
- "vq/commitment_loss" : Tensor[1]
195
- Commitment loss to train encoder to predict vectors closer to codebook
196
- entries
197
- "vq/codebook_loss" : Tensor[1]
198
- Codebook loss to update the codebook
199
- """
200
- z_q = 0
201
- residual = z
202
- commitment_loss = 0
203
- codebook_loss = 0
204
-
205
- codebook_indices = []
206
- latents = []
207
-
208
- if n_quantizers is None:
209
- n_quantizers = self.n_codebooks
210
- if self.training:
211
- n_quantizers = torch.ones((z.shape[0],)) * self.n_codebooks + 1
212
- dropout = torch.randint(1, self.n_codebooks + 1, (z.shape[0],))
213
- n_dropout = int(z.shape[0] * self.quantizer_dropout)
214
- n_quantizers[:n_dropout] = dropout[:n_dropout]
215
- n_quantizers = n_quantizers.to(z.device)
216
- else:
217
- n_quantizers = torch.ones((z.shape[0],)) * n_quantizers + 1
218
- n_quantizers = n_quantizers.to(z.device)
219
-
220
- for i, quantizer in enumerate(self.quantizers):
221
- # if self.training is False and i >= n_quantizers:
222
- # break
223
-
224
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
225
- residual
226
- )
227
-
228
- # Create mask to apply quantizer dropout
229
- mask = (
230
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
231
- )
232
- z_q = z_q + z_q_i * mask[:, None, None]
233
- residual = residual - z_q_i
234
-
235
- # Sum losses
236
- commitment_loss += (commitment_loss_i * mask).mean()
237
- codebook_loss += (codebook_loss_i * mask).mean()
238
-
239
- codebook_indices.append(indices_i)
240
- latents.append(z_e_i)
241
-
242
- codes = torch.stack(codebook_indices, dim=1)
243
- latents = torch.cat(latents, dim=1)
244
-
245
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
246
- for n in range(encodings.shape[1]):
247
- print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
248
- (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
249
- ))
250
-
251
- return z_q, codes, latents, commitment_loss, codebook_loss, n_quantizers.clamp(max=self.n_codebooks).long() - 1
252
-
253
- def from_codes(self, codes: torch.Tensor):
254
- """Given the quantized codes, reconstruct the continuous representation
255
- Parameters
256
- ----------
257
- codes : Tensor[B x N x T]
258
- Quantized discrete representation of input
259
- Returns
260
- -------
261
- Tensor[B x D x T]
262
- Quantized continuous representation of input
263
- """
264
- z_q = 0.0
265
- z_p = []
266
- n_codebooks = codes.shape[1]
267
- for i in range(n_codebooks):
268
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
269
- z_p.append(z_p_i)
270
-
271
- z_q_i = self.quantizers[i].out_proj(z_p_i)
272
- z_q = z_q + z_q_i
273
- return z_q, torch.cat(z_p, dim=1), codes
274
-
275
- def from_latents(self, latents: torch.Tensor):
276
- """Given the unquantized latents, reconstruct the
277
- continuous representation after quantization.
278
-
279
- Parameters
280
- ----------
281
- latents : Tensor[B x N x T]
282
- Continuous representation of input after projection
283
-
284
- Returns
285
- -------
286
- Tensor[B x D x T]
287
- Quantized representation of full-projected space
288
- Tensor[B x D x T]
289
- Quantized representation of latent space
290
- """
291
- z_q = 0
292
- z_p = []
293
- codes = []
294
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
295
-
296
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
297
- 0
298
- ]
299
- for i in range(n_codebooks):
300
- j, k = dims[i], dims[i + 1]
301
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
302
- z_p.append(z_p_i)
303
- codes.append(codes_i)
304
-
305
- z_q_i = self.quantizers[i].out_proj(z_p_i)
306
- z_q = z_q + z_q_i
307
-
308
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
309
-
310
-
311
- if __name__ == "__main__":
312
- rvq = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 4, codebook_size = 1024, codebook_dim = 32, quantizer_dropout = 0.0)
313
- # rvq.eval()
314
- x = torch.randn(16, 1024, 80)
315
- quantized_prompt_embeds, codes, _, commitment_loss, codebook_loss, rvq_usage = rvq(x)
316
- print(quantized_prompt_embeds.shape)
317
- print(codes.shape)
318
- # w/o reconstruction
319
- loss = commitment_loss * 0.25 + codebook_loss * 1.0
320
- # w/ reconstruction
321
- loss = commitment_loss * 0.25 + codebook_loss * 1.0 + (x - quantized_prompt_embeds).abs().mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_randomdrop_freezervq.py DELETED
@@ -1,323 +0,0 @@
1
- # compared with `descript_quantize2`, we use rvq & random_dropout
2
- from typing import Union
3
-
4
- import numpy as np
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from einops import rearrange
9
- from torch.nn.utils import weight_norm
10
-
11
- def WNConv1d(*args, **kwargs):
12
- return weight_norm(nn.Conv1d(*args, **kwargs))
13
-
14
- class VectorQuantize(nn.Module):
15
- """
16
- Implementation of VQ similar to Karpathy's repo:
17
- https://github.com/karpathy/deep-vector-quantization
18
- Additionally uses following tricks from Improved VQGAN
19
- (https://arxiv.org/pdf/2110.04627.pdf):
20
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
21
- for improved codebook usage
22
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
23
- improves training stability
24
- """
25
-
26
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, stale_tolerance: int = 100,dropout_rate=0.1):
27
- super().__init__()
28
- self.codebook_size = codebook_size
29
- self.codebook_dim = codebook_dim
30
- self.dropout_rate = dropout_rate
31
-
32
- self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
33
- self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
34
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
35
- self.register_buffer("stale_counter", torch.zeros(self.codebook_size,))
36
- self.stale_tolerance = stale_tolerance
37
-
38
- def forward(self, z):
39
- """Quantized the input tensor using a fixed codebook and returns
40
- the corresponding codebook vectors
41
-
42
- Parameters
43
- ----------
44
- z : Tensor[B x D x T]
45
-
46
- Returns
47
- -------
48
- Tensor[B x D x T]
49
- Quantized continuous representation of input
50
- Tensor[1]
51
- Commitment loss to train encoder to predict vectors closer to codebook
52
- entries
53
- Tensor[1]
54
- Codebook loss to update the codebook
55
- Tensor[B x T]
56
- Codebook indices (quantized discrete representation of input)
57
- Tensor[B x D x T]
58
- Projected latents (continuous representation of input before quantization)
59
- """
60
-
61
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
62
- z_e = self.in_proj(z) # z_e : (B x D x T)
63
- z_q, indices = self.decode_latents(z_e)
64
-
65
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
66
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
67
-
68
- z_q = (
69
- z_e + (z_q - z_e).detach()
70
- ) # noop in forward pass, straight-through gradient estimator in backward pass
71
-
72
- z_q = self.out_proj(z_q)
73
-
74
- return z_q, commitment_loss, codebook_loss, indices, z_e
75
-
76
- def embed_code(self, embed_id):
77
- return F.embedding(embed_id, self.codebook.weight)
78
-
79
- def decode_code(self, embed_id):
80
- return self.embed_code(embed_id).transpose(1, 2)
81
-
82
- def dropout_code(self,code):
83
- total_elements = code.shape[0] * code.shape[1]
84
- dropout_elements = int(total_elements * self.dropout_rate)
85
- dropout_indices = np.random.choice(np.arange(total_elements), size=dropout_elements, replace=False)
86
- # 对每个选择的元素位置进行替换
87
- for idx in dropout_indices:
88
- # 计算二维索引
89
- i = idx // code.shape[1]
90
- j = idx % code.shape[1]
91
- # 替换元素
92
- code[i, j] = np.random.randint(0, self.codebook_size)
93
- return code
94
-
95
- def decode_latents(self, latents):
96
- encodings = rearrange(latents, "b d t -> (b t) d")
97
- codebook = self.codebook.weight # codebook: (N x D)
98
-
99
- # L2 normalize encodings and codebook (ViT-VQGAN)
100
- encodings = F.normalize(encodings)
101
- codebook = F.normalize(codebook)
102
-
103
- # Compute euclidean distance with codebook
104
- dist = (
105
- encodings.pow(2).sum(1, keepdim=True)
106
- - 2 * encodings @ codebook.t()
107
- + codebook.pow(2).sum(1, keepdim=True).t()
108
- )
109
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
110
- # if self.training:
111
- # print("train")
112
- indices = self.dropout_code(indices)
113
-
114
- # print("indices", indices.shape)
115
- #random replace 10% indices
116
- # if(self.training):
117
-
118
- z_q = self.decode_code(indices)
119
-
120
- if(self.training):
121
- onehots = torch.nn.functional.one_hot(indices, self.codebook_size).float() # B, T, codebook_size
122
- stale_codes = (onehots.sum(0).sum(0) == 0).float()
123
- self.stale_counter = self.stale_counter * stale_codes + stale_codes
124
-
125
- # random replace codes that haven't been used for a while
126
- replace_code = (self.stale_counter == self.stale_tolerance).float() # codebook_size
127
- if replace_code.sum(-1) > 0:
128
- print("Replace {} codes".format(replace_code.sum(-1)))
129
- random_input_idx = torch.randperm(encodings.shape[0])
130
- random_input = encodings[random_input_idx].view(encodings.shape)
131
- if random_input.shape[0] < self.codebook_size:
132
- random_input = torch.cat([random_input]*(self.codebook_size // random_input.shape[0] + 1), 0)
133
- random_input = random_input[:self.codebook_size,:].contiguous() # codebook_size, dim
134
-
135
- self.codebook.weight.data = self.codebook.weight.data * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
136
- self.stale_counter = self.stale_counter * (1 - replace_code)
137
-
138
- return z_q, indices
139
-
140
-
141
- class ResidualVectorQuantize(nn.Module):
142
- """
143
- Introduced in SoundStream: An end2end neural audio codec
144
- https://arxiv.org/abs/2107.03312
145
- """
146
-
147
- def __init__(
148
- self,
149
- input_dim: int = 512,
150
- n_codebooks: int = 9,
151
- codebook_size: int = 1024,
152
- codebook_dim: Union[int, list] = 8,
153
- quantizer_dropout: float = 0.0,
154
- stale_tolerance: int = 100,
155
- dropout_rate=0.1
156
- ):
157
- super().__init__()
158
- if isinstance(codebook_dim, int):
159
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
160
-
161
- self.n_codebooks = n_codebooks
162
- self.codebook_dim = codebook_dim
163
- self.codebook_size = codebook_size
164
-
165
- self.quantizers = nn.ModuleList(
166
- [
167
- VectorQuantize(input_dim, codebook_size, codebook_dim[i], stale_tolerance=stale_tolerance,dropout_rate=dropout_rate)
168
- for i in range(n_codebooks)
169
- ]
170
- )
171
- self.quantizer_dropout = quantizer_dropout
172
-
173
- def forward(self, z, n_quantizers: int = None):
174
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
175
- the corresponding codebook vectors
176
- Parameters
177
- ----------
178
- z : Tensor[B x D x T]
179
- n_quantizers : int, optional
180
- No. of quantizers to use
181
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
182
- Note: if `self.quantizer_dropout` is True, this argument is ignored
183
- when in training mode, and a random number of quantizers is used.
184
- Returns
185
- -------
186
- dict
187
- A dictionary with the following keys:
188
-
189
- "z" : Tensor[B x D x T]
190
- Quantized continuous representation of input
191
- "codes" : Tensor[B x N x T]
192
- Codebook indices for each codebook
193
- (quantized discrete representation of input)
194
- "latents" : Tensor[B x N*D x T]
195
- Projected latents (continuous representation of input before quantization)
196
- "vq/commitment_loss" : Tensor[1]
197
- Commitment loss to train encoder to predict vectors closer to codebook
198
- entries
199
- "vq/codebook_loss" : Tensor[1]
200
- Codebook loss to update the codebook
201
- """
202
- z_q = 0
203
- residual = z
204
- commitment_loss = 0
205
- codebook_loss = 0
206
-
207
- codebook_indices = []
208
- latents = []
209
-
210
- if n_quantizers is None:
211
- n_quantizers = self.n_codebooks
212
- if self.training:
213
- n_quantizers = torch.ones((z.shape[0],)) * self.n_codebooks + 1
214
- dropout = torch.randint(1, self.n_codebooks + 1, (z.shape[0],))
215
- n_dropout = int(z.shape[0] * self.quantizer_dropout)
216
- n_quantizers[:n_dropout] = dropout[:n_dropout]
217
- n_quantizers = n_quantizers.to(z.device)
218
- else:
219
- n_quantizers = torch.ones((z.shape[0],)) * n_quantizers + 1
220
- n_quantizers = n_quantizers.to(z.device)
221
-
222
- for i, quantizer in enumerate(self.quantizers):
223
- # if self.training is False and i >= n_quantizers:
224
- # break
225
-
226
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
227
- residual
228
- )
229
-
230
- # Create mask to apply quantizer dropout
231
- mask = (
232
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
233
- )
234
- z_q = z_q + z_q_i * mask[:, None, None]
235
- residual = residual - z_q_i
236
-
237
- # Sum losses
238
- commitment_loss += (commitment_loss_i * mask).mean()
239
- codebook_loss += (codebook_loss_i * mask).mean()
240
-
241
- codebook_indices.append(indices_i)
242
- latents.append(z_e_i)
243
-
244
- codes = torch.stack(codebook_indices, dim=1)
245
- latents = torch.cat(latents, dim=1)
246
-
247
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
248
- for n in range(encodings.shape[1]):
249
- print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
250
- (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
251
- ))
252
-
253
- return z_q, codes, latents, commitment_loss, codebook_loss, n_quantizers.clamp(max=self.n_codebooks).long() - 1
254
-
255
- def from_codes(self, codes: torch.Tensor):
256
- """Given the quantized codes, reconstruct the continuous representation
257
- Parameters
258
- ----------
259
- codes : Tensor[B x N x T]
260
- Quantized discrete representation of input
261
- Returns
262
- -------
263
- Tensor[B x D x T]
264
- Quantized continuous representation of input
265
- """
266
- z_q = 0.0
267
- z_p = []
268
- n_codebooks = codes.shape[1]
269
- for i in range(n_codebooks):
270
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
271
- z_p.append(z_p_i)
272
-
273
- z_q_i = self.quantizers[i].out_proj(z_p_i)
274
- z_q = z_q + z_q_i
275
- return z_q, torch.cat(z_p, dim=1), codes
276
-
277
- def from_latents(self, latents: torch.Tensor):
278
- """Given the unquantized latents, reconstruct the
279
- continuous representation after quantization.
280
-
281
- Parameters
282
- ----------
283
- latents : Tensor[B x N x T]
284
- Continuous representation of input after projection
285
-
286
- Returns
287
- -------
288
- Tensor[B x D x T]
289
- Quantized representation of full-projected space
290
- Tensor[B x D x T]
291
- Quantized representation of latent space
292
- """
293
- z_q = 0
294
- z_p = []
295
- codes = []
296
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
297
-
298
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
299
- 0
300
- ]
301
- for i in range(n_codebooks):
302
- j, k = dims[i], dims[i + 1]
303
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
304
- z_p.append(z_p_i)
305
- codes.append(codes_i)
306
-
307
- z_q_i = self.quantizers[i].out_proj(z_p_i)
308
- z_q = z_q + z_q_i
309
-
310
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
311
-
312
-
313
- if __name__ == "__main__":
314
- rvq = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 4, codebook_size = 1024, codebook_dim = 32, quantizer_dropout = 0.0)
315
- # rvq.eval()
316
- x = torch.randn(16, 1024, 80)
317
- quantized_prompt_embeds, codes, _, commitment_loss, codebook_loss, rvq_usage = rvq(x)
318
- print(quantized_prompt_embeds.shape)
319
- print(codes.shape)
320
- # w/o reconstruction
321
- loss = commitment_loss * 0.25 + codebook_loss * 1.0
322
- # w/ reconstruction
323
- loss = commitment_loss * 0.25 + codebook_loss * 1.0 + (x - quantized_prompt_embeds).abs().mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/descript_quantize3_simple_vq.py DELETED
@@ -1,299 +0,0 @@
1
- # compared with `descript_quantize2`, we use rvq & random_dropout
2
- from typing import Union
3
-
4
- import numpy as np
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from einops import rearrange
9
- from torch.nn.utils import weight_norm
10
-
11
- def WNConv1d(*args, **kwargs):
12
- return weight_norm(nn.Conv1d(*args, **kwargs))
13
-
14
- class VectorQuantize(nn.Module):
15
- """
16
- Implementation of VQ similar to Karpathy's repo:
17
- https://github.com/karpathy/deep-vector-quantization
18
- Additionally uses following tricks from Improved VQGAN
19
- (https://arxiv.org/pdf/2110.04627.pdf):
20
- 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
21
- for improved codebook usage
22
- 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
23
- improves training stability
24
- """
25
-
26
- def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, stale_tolerance: int = 100):
27
- super().__init__()
28
- self.codebook_size = codebook_size
29
- self.codebook_dim = codebook_dim
30
-
31
- self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
32
- self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
33
- self.codebook = nn.Embedding(codebook_size, codebook_dim)
34
- self.register_buffer("stale_counter", torch.zeros(self.codebook_size,))
35
- self.stale_tolerance = stale_tolerance
36
-
37
- def forward(self, z):
38
- """Quantized the input tensor using a fixed codebook and returns
39
- the corresponding codebook vectors
40
-
41
- Parameters
42
- ----------
43
- z : Tensor[B x D x T]
44
-
45
- Returns
46
- -------
47
- Tensor[B x D x T]
48
- Quantized continuous representation of input
49
- Tensor[1]
50
- Commitment loss to train encoder to predict vectors closer to codebook
51
- entries
52
- Tensor[1]
53
- Codebook loss to update the codebook
54
- Tensor[B x T]
55
- Codebook indices (quantized discrete representation of input)
56
- Tensor[B x D x T]
57
- Projected latents (continuous representation of input before quantization)
58
- """
59
-
60
- # Factorized codes (ViT-VQGAN) Project input into low-dimensional space
61
- z_e = self.in_proj(z) # z_e : (B x D x T)
62
- z_q, indices = self.decode_latents(z_e)
63
-
64
- commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
65
- codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
66
-
67
- z_q = (
68
- z_e + (z_q - z_e).detach()
69
- ) # noop in forward pass, straight-through gradient estimator in backward pass
70
-
71
- z_q = self.out_proj(z_q)
72
-
73
- return z_q, commitment_loss, codebook_loss, indices, z_e
74
-
75
- def embed_code(self, embed_id):
76
- return F.embedding(embed_id, self.codebook.weight)
77
-
78
- def decode_code(self, embed_id):
79
- return self.embed_code(embed_id).transpose(1, 2)
80
-
81
- def decode_latents(self, latents):
82
- encodings = rearrange(latents, "b d t -> (b t) d")
83
- codebook = self.codebook.weight # codebook: (N x D)
84
-
85
- # L2 normalize encodings and codebook (ViT-VQGAN)
86
- encodings = F.normalize(encodings)
87
- codebook = F.normalize(codebook)
88
-
89
- # Compute euclidean distance with codebook
90
- dist = (
91
- encodings.pow(2).sum(1, keepdim=True)
92
- - 2 * encodings @ codebook.t()
93
- + codebook.pow(2).sum(1, keepdim=True).t()
94
- )
95
- indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
96
- z_q = self.decode_code(indices)
97
-
98
- if(self.training):
99
- onehots = torch.nn.functional.one_hot(indices, self.codebook_size).float() # B, T, codebook_size
100
- stale_codes = (onehots.sum(0).sum(0) == 0).float()
101
- self.stale_counter = self.stale_counter * stale_codes + stale_codes
102
-
103
- # random replace codes that haven't been used for a while
104
- replace_code = (self.stale_counter == self.stale_tolerance).float() # codebook_size
105
- if replace_code.sum(-1) > 0:
106
- print("Replace {} codes".format(replace_code.sum(-1)))
107
- random_input_idx = torch.randperm(encodings.shape[0])
108
- random_input = encodings[random_input_idx].view(encodings.shape)
109
- if random_input.shape[0] < self.codebook_size:
110
- random_input = torch.cat([random_input]*(self.codebook_size // random_input.shape[0] + 1), 0)
111
- random_input = random_input[:self.codebook_size,:].contiguous() # codebook_size, dim
112
-
113
- self.codebook.weight.data = self.codebook.weight.data * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
114
- self.stale_counter = self.stale_counter * (1 - replace_code)
115
-
116
- return z_q, indices
117
-
118
-
119
- class ResidualVectorQuantize(nn.Module):
120
- """
121
- Introduced in SoundStream: An end2end neural audio codec
122
- https://arxiv.org/abs/2107.03312
123
- """
124
-
125
- def __init__(
126
- self,
127
- input_dim: int = 512,
128
- n_codebooks: int = 9,
129
- codebook_size: int = 1024,
130
- codebook_dim: Union[int, list] = 8,
131
- quantizer_dropout: float = 0.0,
132
- stale_tolerance: int = 100,
133
- ):
134
- super().__init__()
135
- if isinstance(codebook_dim, int):
136
- codebook_dim = [codebook_dim for _ in range(n_codebooks)]
137
-
138
- self.n_codebooks = n_codebooks
139
- self.codebook_dim = codebook_dim
140
- self.codebook_size = codebook_size
141
-
142
- self.quantizers = nn.ModuleList(
143
- [
144
- VectorQuantize(input_dim, codebook_size, codebook_dim[i], stale_tolerance=stale_tolerance)
145
- for i in range(n_codebooks)
146
- ]
147
- )
148
- self.quantizer_dropout = quantizer_dropout
149
-
150
- def forward(self, z, n_quantizers: int = None):
151
- """Quantized the input tensor using a fixed set of `n` codebooks and returns
152
- the corresponding codebook vectors
153
- Parameters
154
- ----------
155
- z : Tensor[B x D x T]
156
- n_quantizers : int, optional
157
- No. of quantizers to use
158
- (n_quantizers < self.n_codebooks ex: for quantizer dropout)
159
- Note: if `self.quantizer_dropout` is True, this argument is ignored
160
- when in training mode, and a random number of quantizers is used.
161
- Returns
162
- -------
163
- dict
164
- A dictionary with the following keys:
165
-
166
- "z" : Tensor[B x D x T]
167
- Quantized continuous representation of input
168
- "codes" : Tensor[B x N x T]
169
- Codebook indices for each codebook
170
- (quantized discrete representation of input)
171
- "latents" : Tensor[B x N*D x T]
172
- Projected latents (continuous representation of input before quantization)
173
- "vq/commitment_loss" : Tensor[1]
174
- Commitment loss to train encoder to predict vectors closer to codebook
175
- entries
176
- "vq/codebook_loss" : Tensor[1]
177
- Codebook loss to update the codebook
178
- """
179
- z_q = 0
180
- residual = z
181
- commitment_loss = 0
182
- codebook_loss = 0
183
-
184
- codebook_indices = []
185
- latents = []
186
-
187
- if n_quantizers is None:
188
- n_quantizers = self.n_codebooks
189
- if self.training:
190
- n_quantizers = torch.ones((z.shape[0],)) * self.n_codebooks + 1
191
- dropout = torch.randint(1, self.n_codebooks + 1, (z.shape[0],))
192
- n_dropout = int(z.shape[0] * self.quantizer_dropout)
193
- n_quantizers[:n_dropout] = dropout[:n_dropout]
194
- n_quantizers = n_quantizers.to(z.device)
195
- else:
196
- n_quantizers = torch.ones((z.shape[0],)) * n_quantizers + 1
197
- n_quantizers = n_quantizers.to(z.device)
198
-
199
- for i, quantizer in enumerate(self.quantizers):
200
- # if self.training is False and i >= n_quantizers:
201
- # break
202
-
203
- z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(
204
- residual
205
- )
206
-
207
- # Create mask to apply quantizer dropout
208
- mask = (
209
- torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
210
- )
211
- z_q = z_q + z_q_i * mask[:, None, None]
212
- residual = residual - z_q_i
213
-
214
- # Sum losses
215
- commitment_loss += (commitment_loss_i * mask).mean()
216
- codebook_loss += (codebook_loss_i * mask).mean()
217
-
218
- codebook_indices.append(indices_i)
219
- latents.append(z_e_i)
220
-
221
- codes = torch.stack(codebook_indices, dim=1)
222
- latents = torch.cat(latents, dim=1)
223
-
224
- encodings = F.one_hot(codes, self.codebook_size).float() # B N T 1024
225
- for n in range(encodings.shape[1]):
226
- print("Lyaer {}, Ratio of unused vector : {:.1f}".format(n,
227
- (encodings[:,n,:,:].sum(0).sum(0) < 1.0).sum()/torch.numel(encodings[:,n,:,:].sum(0).sum(0) < 1.0) * 100.
228
- ))
229
-
230
- return z_q, codes, latents, commitment_loss, codebook_loss, n_quantizers.clamp(max=self.n_codebooks).long() - 1
231
-
232
- def from_codes(self, codes: torch.Tensor):
233
- """Given the quantized codes, reconstruct the continuous representation
234
- Parameters
235
- ----------
236
- codes : Tensor[B x N x T]
237
- Quantized discrete representation of input
238
- Returns
239
- -------
240
- Tensor[B x D x T]
241
- Quantized continuous representation of input
242
- """
243
- z_q = 0.0
244
- z_p = []
245
- n_codebooks = codes.shape[1]
246
- for i in range(n_codebooks):
247
- z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
248
- z_p.append(z_p_i)
249
-
250
- z_q_i = self.quantizers[i].out_proj(z_p_i)
251
- z_q = z_q + z_q_i
252
- return z_q, torch.cat(z_p, dim=1), codes
253
-
254
- def from_latents(self, latents: torch.Tensor):
255
- """Given the unquantized latents, reconstruct the
256
- continuous representation after quantization.
257
-
258
- Parameters
259
- ----------
260
- latents : Tensor[B x N x T]
261
- Continuous representation of input after projection
262
-
263
- Returns
264
- -------
265
- Tensor[B x D x T]
266
- Quantized representation of full-projected space
267
- Tensor[B x D x T]
268
- Quantized representation of latent space
269
- """
270
- z_q = 0
271
- z_p = []
272
- codes = []
273
- dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
274
-
275
- n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[
276
- 0
277
- ]
278
- for i in range(n_codebooks):
279
- j, k = dims[i], dims[i + 1]
280
- z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
281
- z_p.append(z_p_i)
282
- codes.append(codes_i)
283
-
284
- z_q_i = self.quantizers[i].out_proj(z_p_i)
285
- z_q = z_q + z_q_i
286
-
287
- return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
288
-
289
-
290
- if __name__ == "__main__":
291
- rvq = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 4, codebook_size = 1024, codebook_dim = 32, quantizer_dropout = 0.0)
292
- x = torch.randn(16, 1024, 80)
293
- quantized_prompt_embeds, codes, _, commitment_loss, codebook_loss, rvq_usage = rvq(x)
294
- print(quantized_prompt_embeds.shape)
295
- print(codes.shape)
296
- # w/o reconstruction
297
- loss = commitment_loss * 0.25 + codebook_loss * 1.0
298
- # w/ reconstruction
299
- loss = commitment_loss * 0.25 + codebook_loss * 1.0 + (x - quantized_prompt_embeds).abs().mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/mert_with_kmeans.py DELETED
@@ -1,187 +0,0 @@
1
- import os, sys
2
- from transformers import AutoModel
3
- import torch
4
- from torch import nn
5
- import torchaudio.transforms as T
6
- import einops
7
- import numpy as np
8
- import joblib
9
- from torch.nn.utils.rnn import pad_sequence
10
-
11
-
12
- def make_pad_mask(lengths: torch.Tensor) -> torch.Tensor:
13
- """
14
- Args:
15
- lengths:
16
- A 1-D tensor containing sentence lengths.
17
- Returns:
18
- Return a 2-D bool tensor, where masked positions
19
- are filled with `True` and non-masked positions are
20
- filled with `False`.
21
-
22
- >>> lengths = torch.tensor([1, 3, 2, 5])
23
- >>> make_pad_mask(lengths)
24
- tensor([[False, True, True, True, True],
25
- [False, False, False, True, True],
26
- [False, False, True, True, True],
27
- [False, False, False, False, False]])
28
- """
29
-
30
- assert lengths.ndim == 1, lengths.ndim
31
-
32
- max_len = lengths.max()
33
- n = lengths.size(0)
34
- expaned_lengths = torch.arange(max_len).expand(n, max_len).to(lengths)
35
-
36
- return expaned_lengths >= lengths.unsqueeze(1)
37
-
38
- class KmeansQuantizer(nn.Module):
39
- def __init__(self, centroids) -> None:
40
- super().__init__()
41
- if type(centroids) == np.ndarray:
42
- centroids = torch.from_numpy(centroids)
43
- # self.clusters = nn.Embedding(n_cluster, feature_dim)
44
- self.clusters = nn.Parameter(centroids)
45
-
46
- @classmethod
47
- def from_pretrained(cls, km_path):
48
- km_model = joblib.load(km_path)
49
- centroids = km_model.cluster_centers_
50
- return cls(centroids)
51
-
52
- @property
53
- def n_cluster(self) -> int:
54
- return self.clusters.shape[0]
55
-
56
- @property
57
- def feature_dim(self) -> int:
58
- return self.clusters.shape[1]
59
-
60
-
61
- def forward(self, inp: torch.Tensor):
62
- if inp.ndim == 3 and inp.shape[-1] == self.feature_dim:
63
- return self.feat2indice(inp)
64
- elif inp.ndim < 3:
65
- return self.indice2feat(inp)
66
- else:
67
- raise NotImplementedError
68
-
69
- def feat2indice(self, feat):
70
- '''
71
- feat: B,T,D
72
- '''
73
- batched_cluster_centers = einops.repeat(self.clusters, 'c d -> b c d', b = feat.shape[0])
74
- dists = torch.cdist(feat, batched_cluster_centers, p = 2)
75
- indices = dists.argmin(dim = -1)
76
- return indices
77
-
78
- def indice2feat(self, indice):
79
- '''
80
- indice: B, T
81
- '''
82
- return nn.functional.embedding(input=indice, weight=self.clusters)
83
-
84
- class MERTwithKmeans(nn.Module):
85
- def __init__(self, pretrained_model_name_or_path, kmeans_path=None, sampling_rate=44100, output_layer=-1, mean_pool=1) -> None:
86
- super().__init__()
87
-
88
- # assert pretrained_model_name_or_path in ["MERT-v1-95M", "MERT-v1-330M"]
89
- assert pretrained_model_name_or_path == "MERT-v1-330M"
90
- # loading our model weights
91
- # self.model = AutoModel.from_pretrained(f"vocal2accmpl/model/.cache/models--m-a-p--MERT-v1-95M/snapshots/8881df140a93e2ea270235b5d7be802245e3d2c6", trust_remote_code=True)
92
- self.model = AutoModel.from_pretrained('pretrained/models--m-a-p--MERT-v1-330M/snapshots/af10da70c94a0c849de9cc94b83e12769c4db499', trust_remote_code=True)
93
- # print(self.model)
94
- if kmeans_path is not None:
95
- centroids = joblib.load(kmeans_path).cluster_centers_
96
- self.kmeans = KmeansQuantizer(centroids)
97
- else:
98
- self.kmeans = None
99
-
100
- # loading the corresponding preprocessor config
101
- # self.processor = Wav2Vec2FeatureExtractor.from_pretrained(f"m-a-p/{pretrained_model_name_or_path}",trust_remote_code=True)
102
-
103
- # make sure the sample_rate aligned
104
- self.sampling_rate = sampling_rate
105
- self.resampler = T.Resample(sampling_rate, 24000) if sampling_rate != 24000 else lambda x: x
106
-
107
- self.do_normalization = (pretrained_model_name_or_path == "MERT-v1-95M")
108
- self.output_layer = output_layer
109
- self.mean_pool = mean_pool
110
- assert self.mean_pool % 2 == 1
111
-
112
- @torch.no_grad()
113
- def forward(self, input_audio, seq_len=None, apply_kmeans=True):
114
- '''
115
- input_audio: B,T
116
- seq_len: B,
117
- '''
118
- device = input_audio.device
119
- return_seq_len = True
120
- if seq_len is None:
121
- return_seq_len = False
122
- seq_len = [input_audio.shape[1] for _ in input_audio]
123
-
124
- input_audio = [self.resampler(x[:l]) for x, l in zip(input_audio, seq_len)]
125
- new_seq_len = torch.tensor([len(i) for i in input_audio], device=device)
126
-
127
-
128
- # std_inp = self.processor([x.numpy() for x in input_audio], sampling_rate=24000, return_tensors="pt", padding=True)
129
-
130
- if self.do_normalization:
131
- input_audio = self.zero_mean_unit_var_norm(input_audio, new_seq_len)
132
-
133
- padded_input = pad_sequence(input_audio, batch_first=True)
134
- attention_mask = ~ make_pad_mask(new_seq_len)
135
-
136
- # assert (~(attention_mask == std_inp['attention_mask'])).sum() == 0, f"{attention_mask}, {std_inp['attention_mask']}"
137
- # assert (~(padded_input.to(dtype=std_inp['input_values'].dtype) == std_inp['input_values'])).sum() == 0, f"{torch.sum((padded_input - std_inp['input_values']))}"
138
-
139
- outputs = self.model(input_values=padded_input, attention_mask=attention_mask, output_hidden_states=True)
140
-
141
- output = outputs['hidden_states'][self.output_layer]
142
- output_len = torch.round(new_seq_len.float() / 24000 * 75).long()
143
- # print(output_len)
144
- # output_len = output_len.masked_fill(output_len > output.shape[1], output.shape[1]).long()
145
- output = nn.functional.interpolate(output.transpose(-1,-2), output_len.max().item()).transpose(-1,-2)
146
-
147
- if self.mean_pool > 1:
148
- output_len = output_len // 3
149
- output = nn.functional.avg_pool1d(output.transpose(-1, -2), kernel_size=self.mean_pool, stride=self.mean_pool)
150
- output = output.transpose(-1,-2)
151
- # print(output.shape, output_len)
152
- # print(output.shape, output_len)
153
-
154
-
155
- if apply_kmeans:
156
- output = self.kmeans.feat2indice(output)
157
-
158
- if return_seq_len:
159
- return output, output_len
160
-
161
- return output
162
-
163
-
164
-
165
- # from transformers.models.wav2vec2.feature_extraction_wav2vec2
166
- # rewrite it by pytorch
167
- @staticmethod
168
- def zero_mean_unit_var_norm(
169
- input_values: torch.Tensor, seq_len: torch.Tensor = None, padding_value: float = 0.0
170
- ) -> torch.Tensor:
171
- """
172
- Every array in the list is normalized to have zero mean and unit variance
173
- """
174
- if seq_len is not None:
175
- normed_input_values = []
176
-
177
- for vector, length in zip(input_values, seq_len):
178
- normed_slice = (vector - vector[:length].mean()) / torch.sqrt(vector[:length].var() + 1e-7)
179
- if length < normed_slice.shape[0]:
180
- normed_slice[length:] = padding_value
181
-
182
- normed_input_values.append(normed_slice)
183
- # normed_input_values = torch.stack(normed_input_values, dim=0)
184
- else:
185
- normed_input_values = (input_values - input_values.mean(dim=-1, keepdim=True)) / torch.sqrt(input_values.var(dim=-1, keepdim=True) + 1e-7)
186
-
187
- return normed_input_values
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/libs/rvq/rvq2.py DELETED
@@ -1,149 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import torch.nn.functional as F
4
- import numpy as np
5
-
6
- # https://github.com/bshall/VectorQuantizedVAE/blob/master/model.py
7
- class VQEmbeddingEMA(nn.Module):
8
- def __init__(self, nband, num_code, code_dim, decay=0.99, layer=0):
9
- super(VQEmbeddingEMA, self).__init__()
10
-
11
- self.nband = nband
12
- self.num_code = num_code
13
- self.code_dim = code_dim
14
- self.decay = decay
15
- self.layer = layer
16
- self.stale_tolerance = 50
17
- self.eps = torch.finfo(torch.float32).eps
18
-
19
- if layer == 0:
20
- embedding = torch.empty(nband, num_code, code_dim).normal_()
21
- embedding = embedding / (embedding.pow(2).sum(-1) + self.eps).sqrt().unsqueeze(-1) # TODO
22
- else:
23
- embedding = torch.empty(nband, num_code, code_dim).normal_() / code_dim
24
- embedding[:,0] = embedding[:,0] * 0 # TODO
25
- self.register_buffer("embedding", embedding)
26
- self.register_buffer("ema_weight", self.embedding.clone())
27
- self.register_buffer("ema_count", torch.zeros(self.nband, self.num_code))
28
- self.register_buffer("stale_counter", torch.zeros(nband, self.num_code))
29
-
30
- def forward(self, input):
31
- num_valid_bands = 1
32
- B, C, N, T = input.shape
33
- assert N == self.code_dim
34
- assert C == num_valid_bands
35
-
36
- input_detach = input.detach().permute(0,3,1,2).contiguous().view(B*T, num_valid_bands, self.code_dim) # B*T, nband, dim
37
- embedding = self.embedding[:num_valid_bands,:,:].contiguous()
38
- # distance
39
- eu_dis = input_detach.pow(2).sum(2).unsqueeze(2) + embedding.pow(2).sum(2).unsqueeze(0) # B*T, nband, num_code
40
- eu_dis = eu_dis - 2 * torch.stack([input_detach[:,i].mm(embedding[i].T) for i in range(num_valid_bands)], 1) # B*T, nband, num_code
41
-
42
- # best codes
43
- indices = torch.argmin(eu_dis, dim=-1) # B*T, nband
44
- quantized = []
45
- for i in range(num_valid_bands):
46
- quantized.append(torch.gather(embedding[i], 0, indices[:,i].unsqueeze(-1).expand(-1, self.code_dim))) # B*T, dim
47
- quantized = torch.stack(quantized, 1)
48
- quantized = quantized.view(B, T, C, N).permute(0,2,3,1).contiguous() # B, C, N, T
49
-
50
- # calculate perplexity
51
- encodings = F.one_hot(indices, self.num_code).float() # B*T, nband, num_code
52
- avg_probs = encodings.mean(0) # nband, num_code
53
- perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + self.eps), -1)).mean()
54
-
55
- if self.training:
56
- # EMA update for codebook
57
-
58
- self.ema_count[:num_valid_bands] = self.decay * self.ema_count[:num_valid_bands] + (1 - self.decay) * torch.sum(encodings, dim=0) # nband, num_code
59
-
60
- update_direction = encodings.permute(1,2,0).bmm(input_detach.permute(1,0,2)) # nband, num_code, dim
61
- self.ema_weight[:num_valid_bands] = self.decay * self.ema_weight[:num_valid_bands] + (1 - self.decay) * update_direction # nband, num_code, dim
62
-
63
- # Laplace smoothing on the counters
64
- # make sure the denominator will never be zero
65
- n = torch.sum(self.ema_count[:num_valid_bands], dim=-1, keepdim=True) # nband, 1
66
- self.ema_count[:num_valid_bands] = (self.ema_count[:num_valid_bands] + self.eps) / (n + self.num_code * self.eps) * n # nband, num_code
67
-
68
- self.embedding[:num_valid_bands] = self.ema_weight[:num_valid_bands] / self.ema_count[:num_valid_bands].unsqueeze(-1)
69
-
70
- # calculate code usage
71
- stale_codes = (encodings.sum(0) == 0).float() # nband, num_code
72
- self.stale_counter[:num_valid_bands] = self.stale_counter[:num_valid_bands] * stale_codes + stale_codes
73
- print("Lyaer {}, Ratio of unused vector : {}, {:.1f}, {:.1f}".format(self.layer, encodings.sum(), stale_codes.sum()/torch.numel(stale_codes)*100., (self.stale_counter > self.stale_tolerance //2).sum() /torch.numel(self.stale_counter)*100.))
74
-
75
- # random replace codes that haven't been used for a while
76
- replace_code = (self.stale_counter[:num_valid_bands] == self.stale_tolerance).float() # nband, num_code
77
- if replace_code.sum(-1).max() > 0:
78
- random_input_idx = torch.randperm(input_detach.shape[0])
79
- random_input = input_detach[random_input_idx].view(input_detach.shape)
80
- if random_input.shape[0] < self.num_code:
81
- random_input = torch.cat([random_input]*(self.num_code // random_input.shape[0] + 1), 0)
82
- random_input = random_input[:self.num_code,:].contiguous().transpose(0,1) # nband, num_code, dim
83
-
84
- self.embedding[:num_valid_bands] = self.embedding[:num_valid_bands] * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
85
- self.ema_weight[:num_valid_bands] = self.ema_weight[:num_valid_bands] * (1 - replace_code).unsqueeze(-1) + random_input * replace_code.unsqueeze(-1)
86
- self.ema_count[:num_valid_bands] = self.ema_count[:num_valid_bands] * (1 - replace_code)
87
- self.stale_counter[:num_valid_bands] = self.stale_counter[:num_valid_bands] * (1 - replace_code)
88
-
89
- # TODO:
90
- # code constraints
91
- if self.layer == 0:
92
- self.embedding[:num_valid_bands] = self.embedding[:num_valid_bands] / (self.embedding[:num_valid_bands].pow(2).sum(-1) + self.eps).sqrt().unsqueeze(-1)
93
- # else:
94
- # # make sure there is always a zero code
95
- # self.embedding[:,0] = self.embedding[:,0] * 0
96
- # self.ema_weight[:,0] = self.ema_weight[:,0] * 0
97
-
98
- return quantized, indices.reshape(B, T, -1), perplexity
99
-
100
- class RVQEmbedding(nn.Module):
101
- def __init__(self, nband, code_dim, decay=0.99, num_codes=[1024, 1024]):
102
- super(RVQEmbedding, self).__init__()
103
-
104
- self.nband = nband
105
- self.code_dim = code_dim
106
- self.decay = decay
107
- self.eps = torch.finfo(torch.float32).eps
108
- self.min_max = [10000, -10000]
109
- self.bins = [256+i*8 for i in range(32)]
110
-
111
- self.VQEmbedding = nn.ModuleList([])
112
- for i in range(len(num_codes)):
113
- self.VQEmbedding.append(VQEmbeddingEMA(nband, num_codes[i], code_dim, decay, layer=i))
114
-
115
- def forward(self, input):
116
- norm_value = torch.norm(input, p=2, dim=-2) # b c t
117
- if(norm_value.min()<self.min_max[0]):self.min_max[0]=norm_value.min().cpu().item()
118
- if(norm_value.max()>self.min_max[-1]):self.min_max[-1]=norm_value.max().cpu().item()
119
- print("Min-max : {}".format(self.min_max))
120
- norm_value = (((norm_value - 256) / 20).clamp(min=0, max=7).int() * 20 + 256 + 10).float()
121
- print("Min-max : {}, {}".format(norm_value.min(), norm_value.max()))
122
- input = torch.nn.functional.normalize(input, p = 2, dim = -2)
123
-
124
- quantized_list = []
125
- perplexity_list = []
126
- indices_list = []
127
- c = []
128
-
129
- residual_input = input
130
- for i in range(len(self.VQEmbedding)):
131
- this_quantized, this_indices, this_perplexity = self.VQEmbedding[i](residual_input)
132
- perplexity_list.append(this_perplexity)
133
- indices_list.append(this_indices)
134
- residual_input = residual_input - this_quantized
135
- if i == 0:
136
- quantized_list.append(this_quantized)
137
- else:
138
- quantized_list.append(quantized_list[-1] + this_quantized)
139
-
140
- quantized_list = torch.stack(quantized_list, -1) # b,1,1024,768,1
141
- perplexity_list = torch.stack(perplexity_list, -1)
142
- indices_list = torch.stack(indices_list, -1) # B T 1 codebooknum
143
- latent_loss = 0
144
- for i in range(quantized_list.shape[-1]):
145
- latent_loss = latent_loss + F.mse_loss(input, quantized_list.detach()[:,:,:,:,i])
146
- # TODO: remove unit norm
147
- quantized_list = quantized_list / (quantized_list.pow(2).sum(2) + self.eps).sqrt().unsqueeze(2) # unit norm
148
-
149
- return quantized_list, norm_value, indices_list, latent_loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/model_septoken.py DELETED
@@ -1,675 +0,0 @@
1
- import yaml
2
- import random
3
- import inspect
4
- import numpy as np
5
- import typing as tp
6
- from abc import ABC
7
-
8
- import torch
9
- import torch.nn as nn
10
- import torch.nn.functional as F
11
- import torchaudio
12
-
13
- from einops import repeat
14
- from tools.torch_tools import wav_to_fbank
15
-
16
- from diffusers.utils.torch_utils import randn_tensor
17
- from transformers import HubertModel
18
- from libs.rvq.descript_quantize3 import ResidualVectorQuantize
19
-
20
- from models_gpt.models.gpt2_rope2_time_new_correct_mask_noncasual_reflow import GPT2Model
21
- from models_gpt.models.gpt2_config import GPT2Config
22
- from our_MERT_BESTRQ.mert_fairseq.models.musicfm.musicfm_model import MusicFMModel, MusicFMConfig
23
-
24
- from torch.cuda.amp import autocast
25
-
26
- class HubertModelWithFinalProj(HubertModel):
27
- def __init__(self, config):
28
- super().__init__(config)
29
-
30
- # The final projection layer is only used for backward compatibility.
31
- # Following https://github.com/auspicious3000/contentvec/issues/6
32
- # Remove this layer is necessary to achieve the desired outcome.
33
- print("hidden_size:",config.hidden_size)
34
- print("classifier_proj_size:",config.classifier_proj_size)
35
- self.final_proj = nn.Linear(config.hidden_size, config.classifier_proj_size)
36
-
37
-
38
- class SampleProcessor(torch.nn.Module):
39
- def project_sample(self, x: torch.Tensor):
40
- """Project the original sample to the 'space' where the diffusion will happen."""
41
- """Project back from diffusion space to the actual sample space."""
42
- return z
43
-
44
- class Feature1DProcessor(SampleProcessor):
45
- def __init__(self, dim: int = 100, power_std = 1., \
46
- num_samples: int = 100_000, cal_num_frames: int = 600):
47
- super().__init__()
48
-
49
- self.num_samples = num_samples
50
- self.dim = dim
51
- self.power_std = power_std
52
- self.cal_num_frames = cal_num_frames
53
- self.register_buffer('counts', torch.zeros(1))
54
- self.register_buffer('sum_x', torch.zeros(dim))
55
- self.register_buffer('sum_x2', torch.zeros(dim))
56
- self.register_buffer('sum_target_x2', torch.zeros(dim))
57
- self.counts: torch.Tensor
58
- self.sum_x: torch.Tensor
59
- self.sum_x2: torch.Tensor
60
-
61
- @property
62
- def mean(self):
63
- mean = self.sum_x / self.counts
64
- if(self.counts < 10):
65
- mean = torch.zeros_like(mean)
66
- return mean
67
-
68
- @property
69
- def std(self):
70
- std = (self.sum_x2 / self.counts - self.mean**2).clamp(min=0).sqrt()
71
- if(self.counts < 10):
72
- std = torch.ones_like(std)
73
- return std
74
-
75
- @property
76
- def target_std(self):
77
- return 1
78
-
79
- def project_sample(self, x: torch.Tensor):
80
- assert x.dim() == 3
81
- if self.counts.item() < self.num_samples:
82
- self.counts += len(x)
83
- self.sum_x += x[:,:,0:self.cal_num_frames].mean(dim=(2,)).sum(dim=0)
84
- self.sum_x2 += x[:,:,0:self.cal_num_frames].pow(2).mean(dim=(2,)).sum(dim=0)
85
- rescale = (self.target_std / self.std.clamp(min=1e-12)) ** self.power_std # same output size
86
- x = (x - self.mean.view(1, -1, 1)) * rescale.view(1, -1, 1)
87
- return x
88
-
89
- def return_sample(self, x: torch.Tensor):
90
- assert x.dim() == 3
91
- rescale = (self.std / self.target_std) ** self.power_std
92
- x = x * rescale.view(1, -1, 1) + self.mean.view(1, -1, 1)
93
- return x
94
-
95
- def pad_or_tunc_tolen(prior_text_encoder_hidden_states, prior_text_mask, prior_prompt_embeds, len_size=77):
96
- if(prior_text_encoder_hidden_states.shape[1]<len_size):
97
- prior_text_encoder_hidden_states = torch.cat([prior_text_encoder_hidden_states, \
98
- torch.zeros(prior_text_mask.shape[0], len_size-prior_text_mask.shape[1], \
99
- prior_text_encoder_hidden_states.shape[2], device=prior_text_mask.device, \
100
- dtype=prior_text_encoder_hidden_states.dtype)],1)
101
- prior_text_mask = torch.cat([prior_text_mask, torch.zeros(prior_text_mask.shape[0], len_size-prior_text_mask.shape[1], device=prior_text_mask.device, dtype=prior_text_mask.dtype)],1)
102
- else:
103
- prior_text_encoder_hidden_states = prior_text_encoder_hidden_states[:,0:len_size]
104
- prior_text_mask = prior_text_mask[:,0:len_size]
105
- prior_text_encoder_hidden_states = prior_text_encoder_hidden_states.permute(0,2,1).contiguous()
106
- return prior_text_encoder_hidden_states, prior_text_mask, prior_prompt_embeds
107
-
108
- class BASECFM(torch.nn.Module, ABC):
109
- def __init__(
110
- self,
111
- estimator,
112
- mlp
113
- ):
114
- super().__init__()
115
- self.sigma_min = 1e-4
116
-
117
- self.estimator = estimator
118
- self.mlp = mlp
119
-
120
- @torch.inference_mode()
121
- def forward(self, mu, n_timesteps, temperature=1.0):
122
- """Forward diffusion
123
-
124
- Args:
125
- mu (torch.Tensor): output of encoder
126
- shape: (batch_size, n_channels, mel_timesteps, n_feats)
127
- n_timesteps (int): number of diffusion steps
128
- temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
129
-
130
- Returns:
131
- sample: generated mel-spectrogram
132
- shape: (batch_size, n_channels, mel_timesteps, n_feats)
133
- """
134
- z = torch.randn_like(mu) * temperature
135
- t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device)
136
- return self.solve_euler(z, t_span=t_span)
137
-
138
- def solve_euler(self, x, latent_mask_input,incontext_x, incontext_length, t_span, mu,attention_mask, guidance_scale):
139
- """
140
- Fixed euler solver for ODEs.
141
- Args:
142
- x (torch.Tensor): random noise
143
- t_span (torch.Tensor): n_timesteps interpolated
144
- shape: (n_timesteps + 1,)
145
- mu (torch.Tensor): output of encoder
146
- shape: (batch_size, n_channels, mel_timesteps, n_feats)
147
- """
148
- dt = t_span[1:] - t_span[:-1]
149
- t = t_span[:-1]
150
- B = x.shape[0]
151
-
152
- if guidance_scale > 1.0:
153
- def double(z):
154
- return torch.cat([z, z], 0) if z is not None else None
155
- attention_mask = double(attention_mask)
156
-
157
- x_next = x.clone()
158
- noise = x.clone()
159
-
160
- for i in range(len(dt)):
161
- ti = t[i]
162
-
163
- x_next[:, :incontext_length] = (
164
- (1 - (1 - self.sigma_min) * ti) * noise[:, :incontext_length] +
165
- ti * incontext_x[:, :incontext_length]
166
- )
167
-
168
- if guidance_scale > 1.0:
169
- model_input = torch.cat([
170
- double(latent_mask_input),
171
- double(incontext_x),
172
- torch.cat([torch.zeros_like(mu), mu], 0),
173
- double(x_next),
174
- ], dim=2)
175
- timestep = ti.expand(2 * B)
176
- else:
177
- model_input = torch.cat([
178
- latent_mask_input, incontext_x, mu, x_next
179
- ], dim=2)
180
- timestep = ti.expand(B)
181
-
182
- v = self.estimator(inputs_embeds=model_input,
183
- attention_mask=attention_mask,
184
- time_step=timestep).last_hidden_state
185
- v = v[..., -x.shape[2]:]
186
-
187
- if guidance_scale > 1.0:
188
- v_uncond, v_cond = v.chunk(2, 0)
189
- v = v_uncond + guidance_scale * (v_cond - v_uncond)
190
-
191
- x_next = x_next + dt[i] * v
192
-
193
- return x_next
194
-
195
- def projection_loss(self,hidden_proj, bestrq_emb):
196
- bsz = hidden_proj.shape[0]
197
-
198
- hidden_proj_normalized = F.normalize(hidden_proj, dim=-1)
199
- bestrq_emb_normalized = F.normalize(bestrq_emb, dim=-1)
200
-
201
- proj_loss = -(hidden_proj_normalized * bestrq_emb_normalized).sum(dim=-1)
202
- proj_loss = 1+proj_loss.mean()
203
-
204
- return proj_loss
205
-
206
- def compute_loss(self, x1, mu, latent_masks,attention_mask,wav2vec_embeds, validation_mode=False):
207
- """Computes diffusion loss
208
-
209
- Args:
210
- x1 (torch.Tensor): Target
211
- shape: (batch_size, n_channels, mel_timesteps, n_feats)
212
- mu (torch.Tensor): output of encoder
213
- shape: (batch_size, n_channels, mel_timesteps, n_feats)
214
-
215
- Returns:
216
- loss: conditional flow matching loss
217
- y: conditional flow
218
- shape: (batch_size, n_channels, mel_timesteps, n_feats)
219
- """
220
- b = mu[0].shape[0]
221
- len_x = x1.shape[2]
222
- # random timestep
223
- if(validation_mode):
224
- t = torch.ones([b, 1, 1], device=mu[0].device, dtype=mu[0].dtype) * 0.5
225
- else:
226
- t = torch.rand([b, 1, 1], device=mu[0].device, dtype=mu[0].dtype)
227
- # sample noise p(x_0)
228
- z = torch.randn_like(x1)
229
-
230
- y = (1 - (1 - self.sigma_min) * t) * z + t * x1
231
- u = x1 - (1 - self.sigma_min) * z
232
- model_input = torch.cat([*mu,y], 2)
233
- t=t.squeeze(-1).squeeze(-1)
234
- out = self.estimator(inputs_embeds=model_input, attention_mask=attention_mask,time_step=t,output_hidden_states=True)
235
- hidden_layer_7 = out.hidden_states[7]
236
- hidden_proj = self.mlp(hidden_layer_7)
237
- out = out.last_hidden_state
238
- out=out[:,:,-len_x:]
239
-
240
- weight = (latent_masks > 1.5).unsqueeze(-1).repeat(1, 1, out.shape[-1]).float() + (latent_masks < 0.5).unsqueeze(-1).repeat(1, 1, out.shape[-1]).float() * 0.01
241
- loss_re = F.mse_loss(out * weight, u * weight, reduction="sum") / weight.sum()
242
- loss_cos = self.projection_loss(hidden_proj, wav2vec_embeds)
243
- loss = loss_re + loss_cos * 0.5
244
- return loss, loss_re, loss_cos
245
-
246
- class PromptCondAudioDiffusion(nn.Module):
247
- def __init__(
248
- self,
249
- num_channels,
250
- unet_model_name=None,
251
- unet_model_config_path=None,
252
- snr_gamma=None,
253
- uncondition=True,
254
- ):
255
- super().__init__()
256
-
257
- assert unet_model_name is not None or unet_model_config_path is not None, "Either UNet pretrain model name or a config file path is required"
258
-
259
- self.unet_model_name = unet_model_name
260
- self.unet_model_config_path = unet_model_config_path
261
- self.snr_gamma = snr_gamma
262
- self.uncondition = uncondition
263
- self.num_channels = num_channels
264
-
265
- # https://huggingface.co/docs/diffusers/v0.14.0/en/api/schedulers/overview
266
- self.normfeat = Feature1DProcessor(dim=64)
267
-
268
- self.sample_rate = 48000
269
- self.num_samples_perseg = self.sample_rate * 20 // 1000
270
- self.rsp48toclap = torchaudio.transforms.Resample(48000, 24000)
271
- self.rsq48towav2vec = torchaudio.transforms.Resample(48000, 16000)
272
- # self.wav2vec = Wav2Vec2BertModel.from_pretrained("facebook/w2v-bert-2.0", trust_remote_code=True)
273
- # self.wav2vec_processor = AutoFeatureExtractor.from_pretrained("facebook/w2v-bert-2.0", trust_remote_code=True)
274
- self.bestrq = MusicFMModel(MusicFMConfig())
275
- self.rsq48tobestrq = torchaudio.transforms.Resample(48000, 24000)
276
- self.rsq48tohubert = torchaudio.transforms.Resample(48000, 16000)
277
- self.rvq_bestrq_emb = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 1, codebook_size = 16_384, codebook_dim = 32, quantizer_dropout = 0.0, stale_tolerance=200)
278
- self.rvq_bestrq_bgm_emb = ResidualVectorQuantize(input_dim = 1024, n_codebooks = 1, codebook_size = 16_384, codebook_dim = 32, quantizer_dropout = 0.0, stale_tolerance=200)
279
- # self.hubert = HubertModelWithFinalProj.from_pretrained("ckpt/models--lengyue233--content-vec-best/snapshots/c0b9ba13db21beaa4053faae94c102ebe326fd68")
280
- # for v in self.hubert.parameters():v.requires_grad = False
281
- self.zero_cond_embedding1 = nn.Parameter(torch.randn(32*32,))
282
- # self.xvecmodel = XVECModel()
283
- config = GPT2Config(n_positions=1000,n_layer=16,n_head=20,n_embd=2200,n_inner=4400)
284
- unet = GPT2Model(config)
285
- mlp = nn.Sequential(
286
- nn.Linear(2200, 1024),
287
- nn.SiLU(),
288
- nn.Linear(1024, 1024),
289
- nn.SiLU(),
290
- nn.Linear(1024, 768)
291
- )
292
- self.set_from = "random"
293
- self.cfm_wrapper = BASECFM(unet, mlp)
294
- self.mask_emb = torch.nn.Embedding(3, 24)
295
- print("Transformer initialized from pretrain.")
296
- torch.cuda.empty_cache()
297
-
298
- def compute_snr(self, timesteps):
299
- """
300
- Computes SNR as per https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
301
- """
302
- alphas_cumprod = self.noise_scheduler.alphas_cumprod
303
- sqrt_alphas_cumprod = alphas_cumprod**0.5
304
- sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
305
-
306
- # Expand the tensors.
307
- # Adapted from https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L1026
308
- sqrt_alphas_cumprod = sqrt_alphas_cumprod.to(device=timesteps.device)[timesteps].float()
309
- while len(sqrt_alphas_cumprod.shape) < len(timesteps.shape):
310
- sqrt_alphas_cumprod = sqrt_alphas_cumprod[..., None]
311
- alpha = sqrt_alphas_cumprod.expand(timesteps.shape)
312
-
313
- sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(device=timesteps.device)[timesteps].float()
314
- while len(sqrt_one_minus_alphas_cumprod.shape) < len(timesteps.shape):
315
- sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod[..., None]
316
- sigma = sqrt_one_minus_alphas_cumprod.expand(timesteps.shape)
317
-
318
- # Compute SNR.
319
- snr = (alpha / sigma) ** 2
320
- return snr
321
-
322
- def preprocess_audio(self, input_audios, threshold=0.9):
323
- assert len(input_audios.shape) == 2, input_audios.shape
324
- norm_value = torch.ones_like(input_audios[:,0])
325
- max_volume = input_audios.abs().max(dim=-1)[0]
326
- norm_value[max_volume>threshold] = max_volume[max_volume>threshold] / threshold
327
- return input_audios/norm_value.unsqueeze(-1)
328
-
329
- def extract_wav2vec_embeds(self, input_audios,output_len):
330
- wav2vec_stride = 2
331
-
332
- wav2vec_embeds = self.hubert(self.rsq48tohubert(input_audios), output_hidden_states=True).hidden_states # 1, 4096, 1024
333
- wav2vec_embeds_last=wav2vec_embeds[-1]
334
- wav2vec_embeds_last=torch.nn.functional.interpolate(wav2vec_embeds_last.permute(0, 2, 1), size=output_len, mode='linear', align_corners=False).permute(0, 2, 1)
335
- return wav2vec_embeds_last
336
-
337
- def extract_mert_embeds(self, input_audios):
338
- prompt_stride = 3
339
- inputs = self.clap_embd_extractor.mulan.audio.processor(self.rsp48toclap(input_audios), sampling_rate=self.clap_embd_extractor.mulan.audio.sr, return_tensors="pt")
340
- input_values = inputs['input_values'].squeeze(0).to(input_audios.device, dtype = input_audios.dtype)
341
- prompt_embeds = self.clap_embd_extractor.mulan.audio.model(input_values, output_hidden_states=True).hidden_states # batch_size, Time steps, 1024
342
- mert_emb= prompt_embeds[-1]
343
- mert_emb = torch.nn.functional.interpolate(mert_emb.permute(0, 2, 1), size=375, mode='linear', align_corners=False).permute(0, 2, 1)
344
-
345
- return mert_emb
346
-
347
- def extract_bestrq_embeds(self, input_audio_vocal_0,input_audio_vocal_1,layer):
348
- input_wav_mean = (input_audio_vocal_0 + input_audio_vocal_1) / 2.0
349
- input_wav_mean = self.bestrq(self.rsq48tobestrq(input_wav_mean), features_only = True)
350
- layer_results = input_wav_mean['layer_results']
351
- bestrq_emb = layer_results[layer]
352
- bestrq_emb = bestrq_emb.permute(0,2,1).contiguous()
353
- return bestrq_emb
354
-
355
-
356
- def extract_spk_embeds(self, input_audios):
357
- spk_embeds = self.xvecmodel(self.rsq48towav2vec(input_audios))
358
- spk_embeds = self.spk_linear(spk_embeds).reshape(spk_embeds.shape[0], 16, 1, 32)
359
- return spk_embeds
360
-
361
- def extract_lyric_feats(self, lyric):
362
- with torch.no_grad():
363
- try:
364
- text_encoder_hidden_states, text_mask, text_prompt_embeds = self.clap_embd_extractor(texts = lyric, return_one=False)
365
- except:
366
- text_encoder_hidden_states, text_mask, text_prompt_embeds = self.clap_embd_extractor(texts = [""] * len(lyric), return_one=False)
367
- text_encoder_hidden_states = text_encoder_hidden_states.to(self.device)
368
- text_mask = text_mask.to(self.device)
369
- text_encoder_hidden_states, text_mask, text_prompt_embeds = \
370
- pad_or_tunc_tolen(text_encoder_hidden_states, text_mask, text_prompt_embeds)
371
- text_encoder_hidden_states = text_encoder_hidden_states.permute(0,2,1).contiguous()
372
- return text_encoder_hidden_states, text_mask
373
-
374
- def extract_energy_bar(self, input_audios):
375
- if(input_audios.shape[-1] % self.num_samples_perseg > 0):
376
- energy_bar = input_audios[:,:-1 * (input_audios.shape[-1] % self.num_samples_perseg)].reshape(input_audios.shape[0],-1,self.num_samples_perseg)
377
- else:
378
- energy_bar = input_audios.reshape(input_audios.shape[0],-1,self.num_samples_perseg)
379
- energy_bar = (energy_bar.pow(2.0).mean(-1).sqrt() + 1e-6).log10() * 20 # B T
380
- energy_bar = (energy_bar / 2.0 + 16).clamp(0,16).int()
381
- energy_embedding = self.energy_embedding(energy_bar)
382
- energy_embedding = energy_embedding.view(energy_embedding.shape[0], energy_embedding.shape[1] // 2, 2, 32).reshape(energy_embedding.shape[0], energy_embedding.shape[1] // 2, 64).permute(0,2,1) # b 128 t
383
- return energy_embedding
384
-
385
- def forward(self, input_audios_vocal,input_audios_bgm, lyric, latents, latent_masks, validation_mode=False, \
386
- additional_feats = ['spk', 'lyric'], \
387
- train_rvq=True, train_ssl=False,layer_vocal=7,layer_bgm=7):
388
- if not hasattr(self,"device"):
389
- self.device = input_audios_vocal.device
390
- if not hasattr(self,"dtype"):
391
- self.dtype = input_audios_vocal.dtype
392
- device = self.device
393
- input_audio_vocal_0 = input_audios_vocal[:,0,:]
394
- input_audio_vocal_1 = input_audios_vocal[:,1,:]
395
- input_audio_vocal_0 = self.preprocess_audio(input_audio_vocal_0)
396
- input_audio_vocal_1 = self.preprocess_audio(input_audio_vocal_1)
397
- input_audios_vocal_wav2vec = (input_audio_vocal_0 + input_audio_vocal_1) / 2.0
398
-
399
- input_audio_bgm_0 = input_audios_bgm[:,0,:]
400
- input_audio_bgm_1 = input_audios_bgm[:,1,:]
401
- input_audio_bgm_0 = self.preprocess_audio(input_audio_bgm_0)
402
- input_audio_bgm_1 = self.preprocess_audio(input_audio_bgm_1)
403
- input_audios_bgm_wav2vec = (input_audio_bgm_0 + input_audio_bgm_1) / 2.0
404
-
405
- if(train_ssl):
406
- self.wav2vec.train()
407
- wav2vec_embeds = self.extract_wav2vec_embeds(input_audios)
408
- self.clap_embd_extractor.train()
409
- prompt_embeds = self.extract_mert_embeds(input_audios)
410
- if('spk' in additional_feats):
411
- self.xvecmodel.train()
412
- spk_embeds = self.extract_spk_embeds(input_audios).repeat(1,1,prompt_embeds.shape[-1]//2,1)
413
- else:
414
- with torch.no_grad():
415
- with autocast(enabled=False):
416
- bestrq_emb = self.extract_bestrq_embeds(input_audio_vocal_0,input_audio_vocal_1,layer_vocal)
417
- bestrq_emb_bgm = self.extract_bestrq_embeds(input_audio_bgm_0,input_audio_bgm_1,layer_bgm)
418
- # mert_emb = self.extract_mert_embeds(input_audios_mert)
419
- output_len = bestrq_emb.shape[2]
420
- wav2vec_embeds = self.extract_wav2vec_embeds(input_audios_vocal_wav2vec+input_audios_bgm_wav2vec,output_len)
421
-
422
-
423
- bestrq_emb = bestrq_emb.detach()
424
- bestrq_emb_bgm = bestrq_emb_bgm.detach()
425
-
426
- if('lyric' in additional_feats):
427
- text_encoder_hidden_states, text_mask = self.extract_lyric_feats(lyric)
428
- else:
429
- text_encoder_hidden_states, text_mask = None, None
430
-
431
-
432
- if(train_rvq):
433
- quantized_bestrq_emb, _, _, commitment_loss_bestrq_emb, codebook_loss_bestrq_emb,_ = self.rvq_bestrq_emb(bestrq_emb) # b,d,t
434
- quantized_bestrq_emb_bgm, _, _, commitment_loss_bestrq_emb_bgm, codebook_loss_bestrq_emb_bgm,_ = self.rvq_bestrq_bgm_emb(bestrq_emb_bgm) # b,d,t
435
- else:
436
- bestrq_emb = bestrq_emb.float()
437
- self.rvq_bestrq_emb.eval()
438
- # with autocast(enabled=False):
439
- quantized_bestrq_emb, _, _, commitment_loss_bestrq_emb, codebook_loss_bestrq_emb,_ = self.rvq_bestrq_emb(bestrq_emb) # b,d,t
440
- commitment_loss_bestrq_emb = commitment_loss_bestrq_emb.detach()
441
- codebook_loss_bestrq_emb = codebook_loss_bestrq_emb.detach()
442
- quantized_bestrq_emb = quantized_bestrq_emb.detach()
443
-
444
- commitment_loss = commitment_loss_bestrq_emb+commitment_loss_bestrq_emb_bgm
445
- codebook_loss = codebook_loss_bestrq_emb+codebook_loss_bestrq_emb_bgm
446
-
447
-
448
- alpha=1
449
- quantized_bestrq_emb = quantized_bestrq_emb * alpha + bestrq_emb * (1-alpha)
450
- quantized_bestrq_emb_bgm = quantized_bestrq_emb_bgm * alpha + bestrq_emb_bgm * (1-alpha)
451
-
452
-
453
-
454
-
455
- scenario = np.random.choice(['start_seg', 'other_seg'])
456
- if(scenario == 'other_seg'):
457
- for binx in range(input_audios_vocal.shape[0]):
458
- # latent_masks[binx,0:64] = 1
459
- latent_masks[binx,0:random.randint(64,128)] = 1
460
- quantized_bestrq_emb = quantized_bestrq_emb.permute(0,2,1).contiguous()
461
- quantized_bestrq_emb_bgm = quantized_bestrq_emb_bgm.permute(0,2,1).contiguous()
462
- quantized_bestrq_emb = (latent_masks > 0.5).unsqueeze(-1) * quantized_bestrq_emb \
463
- + (latent_masks < 0.5).unsqueeze(-1) * self.zero_cond_embedding1.reshape(1,1,1024)
464
- quantized_bestrq_emb_bgm = (latent_masks > 0.5).unsqueeze(-1) * quantized_bestrq_emb_bgm \
465
- + (latent_masks < 0.5).unsqueeze(-1) * self.zero_cond_embedding1.reshape(1,1,1024)
466
-
467
-
468
-
469
-
470
- if self.uncondition:
471
- mask_indices = [k for k in range(quantized_bestrq_emb.shape[0]) if random.random() < 0.1]
472
- if len(mask_indices) > 0:
473
- quantized_bestrq_emb[mask_indices] = 0
474
- quantized_bestrq_emb_bgm[mask_indices] = 0
475
- latents = latents.permute(0,2,1).contiguous()
476
- latents = self.normfeat.project_sample(latents)
477
- latents = latents.permute(0,2,1).contiguous()
478
- incontext_latents = latents * ((latent_masks > 0.5) * (latent_masks < 1.5)).unsqueeze(-1).float()
479
- attention_mask=(latent_masks > 0.5)
480
- B, L = attention_mask.size()
481
- attention_mask = attention_mask.view(B, 1, L)
482
- attention_mask = attention_mask * attention_mask.transpose(-1, -2)
483
- attention_mask = attention_mask.unsqueeze(1)
484
- latent_mask_input = self.mask_emb(latent_masks)
485
- loss,loss_re, loss_cos = self.cfm_wrapper.compute_loss(latents, [latent_mask_input,incontext_latents, quantized_bestrq_emb,quantized_bestrq_emb_bgm], latent_masks,attention_mask,wav2vec_embeds, validation_mode=validation_mode)
486
- return loss,loss_re, loss_cos, commitment_loss.mean(), codebook_loss.mean()
487
-
488
- def init_device_dtype(self, device, dtype):
489
- self.device = device
490
- self.dtype = dtype
491
-
492
- @torch.no_grad()
493
- def fetch_codes(self, input_audios_vocal,input_audios_bgm, additional_feats,layer_vocal=7,layer_bgm=7):
494
- input_audio_vocal_0 = input_audios_vocal[[0],:]
495
- input_audio_vocal_1 = input_audios_vocal[[1],:]
496
- input_audio_vocal_0 = self.preprocess_audio(input_audio_vocal_0)
497
- input_audio_vocal_1 = self.preprocess_audio(input_audio_vocal_1)
498
- input_audios_vocal_wav2vec = (input_audio_vocal_0 + input_audio_vocal_1) / 2.0
499
-
500
- input_audio_bgm_0 = input_audios_bgm[[0],:]
501
- input_audio_bgm_1 = input_audios_bgm[[1],:]
502
- input_audio_bgm_0 = self.preprocess_audio(input_audio_bgm_0)
503
- input_audio_bgm_1 = self.preprocess_audio(input_audio_bgm_1)
504
- input_audios_bgm_wav2vec = (input_audio_bgm_0 + input_audio_bgm_1) / 2.0
505
-
506
- self.bestrq.eval()
507
-
508
- # bestrq_middle,bestrq_last = self.extract_bestrq_embeds(input_audios)
509
- # bestrq_middle = bestrq_middle.detach()
510
- # bestrq_last = bestrq_last.detach()
511
- bestrq_emb = self.extract_bestrq_embeds(input_audio_vocal_0,input_audio_vocal_1,layer_vocal)
512
- bestrq_emb = bestrq_emb.detach()
513
-
514
- bestrq_emb_bgm = self.extract_bestrq_embeds(input_audio_bgm_0,input_audio_bgm_1,layer_bgm)
515
- bestrq_emb_bgm = bestrq_emb_bgm.detach()
516
-
517
-
518
-
519
- self.rvq_bestrq_emb.eval()
520
- quantized_bestrq_emb, codes_bestrq_emb, *_ = self.rvq_bestrq_emb(bestrq_emb) # b,d,t
521
-
522
- self.rvq_bestrq_bgm_emb.eval()
523
- quantized_bestrq_emb_bgm, codes_bestrq_emb_bgm, *_ = self.rvq_bestrq_bgm_emb(bestrq_emb_bgm) # b,d,t
524
-
525
-
526
- if('spk' in additional_feats):
527
- self.xvecmodel.eval()
528
- spk_embeds = self.extract_spk_embeds(input_audios)
529
- else:
530
- spk_embeds = None
531
-
532
- # return [codes_prompt, codes_wav2vec], [prompt_embeds, wav2vec_embeds], spk_embeds
533
- # return [codes_prompt_7, codes_prompt_13, codes_prompt_20, codes_wav2vec_half, codes_wav2vec_last], [prompt_embeds_7, prompt_embeds_13, prompt_embeds_20, wav2vec_embeds_half, wav2vec_embeds_last], spk_embeds
534
- # return [codes_bestrq_middle, codes_bestrq_last], [bestrq_middle, bestrq_last], spk_embeds
535
- return [codes_bestrq_emb,codes_bestrq_emb_bgm], [bestrq_emb,bestrq_emb_bgm], spk_embeds
536
- # return [codes_prompt_13, codes_wav2vec_last], [prompt_embeds_13, wav2vec_embeds_last], spk_embeds
537
-
538
- @torch.no_grad()
539
- def fetch_codes_batch(self, input_audios_vocal, input_audios_bgm, additional_feats,layer_vocal=7,layer_bgm=7):
540
- input_audio_vocal_0 = input_audios_vocal[:,0,:]
541
- input_audio_vocal_1 = input_audios_vocal[:,1,:]
542
- input_audio_vocal_0 = self.preprocess_audio(input_audio_vocal_0)
543
- input_audio_vocal_1 = self.preprocess_audio(input_audio_vocal_1)
544
- input_audios_vocal_wav2vec = (input_audio_vocal_0 + input_audio_vocal_1) / 2.0
545
-
546
- input_audio_bgm_0 = input_audios_bgm[:,0,:]
547
- input_audio_bgm_1 = input_audios_bgm[:,1,:]
548
- input_audio_bgm_0 = self.preprocess_audio(input_audio_bgm_0)
549
- input_audio_bgm_1 = self.preprocess_audio(input_audio_bgm_1)
550
- input_audios_bgm_wav2vec = (input_audio_bgm_0 + input_audio_bgm_1) / 2.0
551
-
552
- self.bestrq.eval()
553
-
554
- # bestrq_middle,bestrq_last = self.extract_bestrq_embeds(input_audios)
555
- # bestrq_middle = bestrq_middle.detach()
556
- # bestrq_last = bestrq_last.detach()
557
- bestrq_emb = self.extract_bestrq_embeds(input_audio_vocal_0,input_audio_vocal_1,layer_vocal)
558
- bestrq_emb = bestrq_emb.detach()
559
-
560
- bestrq_emb_bgm = self.extract_bestrq_embeds(input_audio_bgm_0,input_audio_bgm_1,layer_bgm)
561
- bestrq_emb_bgm = bestrq_emb_bgm.detach()
562
-
563
-
564
-
565
- self.rvq_bestrq_emb.eval()
566
- quantized_bestrq_emb, codes_bestrq_emb, *_ = self.rvq_bestrq_emb(bestrq_emb) # b,d,t
567
-
568
- self.rvq_bestrq_bgm_emb.eval()
569
- quantized_bestrq_emb_bgm, codes_bestrq_emb_bgm, *_ = self.rvq_bestrq_bgm_emb(bestrq_emb_bgm) # b,d,t
570
-
571
-
572
- if('spk' in additional_feats):
573
- self.xvecmodel.eval()
574
- spk_embeds = self.extract_spk_embeds(input_audios)
575
- else:
576
- spk_embeds = None
577
-
578
- # return [codes_prompt, codes_wav2vec], [prompt_embeds, wav2vec_embeds], spk_embeds
579
- # return [codes_prompt_7, codes_prompt_13, codes_prompt_20, codes_wav2vec_half, codes_wav2vec_last], [prompt_embeds_7, prompt_embeds_13, prompt_embeds_20, wav2vec_embeds_half, wav2vec_embeds_last], spk_embeds
580
- # return [codes_bestrq_middle, codes_bestrq_last], [bestrq_middle, bestrq_last], spk_embeds
581
- return [codes_bestrq_emb,codes_bestrq_emb_bgm], [bestrq_emb,bestrq_emb_bgm], spk_embeds
582
- # return [codes_prompt_13, codes_wav2vec_last], [prompt_embeds_13, wav2vec_embeds_last], spk_embeds
583
-
584
-
585
- @torch.no_grad()
586
- def inference_codes(self, codes, spk_embeds, true_latents, latent_length, additional_feats,incontext_length=127,
587
- guidance_scale=2, num_steps=20,
588
- disable_progress=True, scenario='start_seg'):
589
- classifier_free_guidance = guidance_scale > 1.0
590
- device = self.device
591
- dtype = self.dtype
592
- # codes_bestrq_middle, codes_bestrq_last = codes
593
- codes_bestrq_emb,codes_bestrq_emb_bgm = codes
594
-
595
-
596
- batch_size = codes_bestrq_emb.shape[0]
597
-
598
-
599
- quantized_bestrq_emb,_,_=self.rvq_bestrq_emb.from_codes(codes_bestrq_emb)
600
- quantized_bestrq_emb_bgm,_,_=self.rvq_bestrq_bgm_emb.from_codes(codes_bestrq_emb_bgm)
601
- quantized_bestrq_emb = quantized_bestrq_emb.permute(0,2,1).contiguous()
602
- quantized_bestrq_emb_bgm = quantized_bestrq_emb_bgm.permute(0,2,1).contiguous()
603
- if('spk' in additional_feats):
604
- spk_embeds = spk_embeds.repeat(1,1,quantized_bestrq_emb.shape[-2],1).detach()
605
-
606
- num_frames = quantized_bestrq_emb.shape[1]
607
-
608
- num_channels_latents = self.num_channels
609
- shape = (batch_size, num_frames, 64)
610
- latents = randn_tensor(shape, generator=None, device=device, dtype=dtype)
611
-
612
-
613
-
614
- latent_masks = torch.zeros(latents.shape[0], latents.shape[1], dtype=torch.int64, device=latents.device)
615
- latent_masks[:,0:latent_length] = 2
616
- if(scenario=='other_seg'):
617
- latent_masks[:,0:incontext_length] = 1
618
-
619
-
620
-
621
- quantized_bestrq_emb = (latent_masks > 0.5).unsqueeze(-1) * quantized_bestrq_emb \
622
- + (latent_masks < 0.5).unsqueeze(-1) * self.zero_cond_embedding1.reshape(1,1,1024)
623
- quantized_bestrq_emb_bgm = (latent_masks > 0.5).unsqueeze(-1) * quantized_bestrq_emb_bgm \
624
- + (latent_masks < 0.5).unsqueeze(-1) * self.zero_cond_embedding1.reshape(1,1,1024)
625
- true_latents = true_latents.permute(0,2,1).contiguous()
626
- true_latents = self.normfeat.project_sample(true_latents)
627
- true_latents = true_latents.permute(0,2,1).contiguous()
628
- incontext_latents = true_latents * ((latent_masks > 0.5) * (latent_masks < 1.5)).unsqueeze(-1).float()
629
- incontext_length = ((latent_masks > 0.5) * (latent_masks < 1.5)).sum(-1)[0]
630
-
631
-
632
- attention_mask=(latent_masks > 0.5)
633
- B, L = attention_mask.size()
634
- attention_mask = attention_mask.view(B, 1, L)
635
- attention_mask = attention_mask * attention_mask.transpose(-1, -2)
636
- attention_mask = attention_mask.unsqueeze(1)
637
- latent_mask_input = self.mask_emb(latent_masks)
638
-
639
- if('spk' in additional_feats):
640
- # additional_model_input = torch.cat([quantized_bestrq_middle, quantized_bestrq_last, spk_embeds],1)
641
- additional_model_input = torch.cat([quantized_bestrq_emb,quantized_bestrq_emb_bgm, spk_embeds],2)
642
- else:
643
- # additional_model_input = torch.cat([quantized_bestrq_middle, quantized_bestrq_last],1)
644
- additional_model_input = torch.cat([quantized_bestrq_emb,quantized_bestrq_emb_bgm],2)
645
-
646
- temperature = 1.0
647
- t_span = torch.linspace(0, 1, num_steps + 1, device=quantized_bestrq_emb.device)
648
- latents = self.cfm_wrapper.solve_euler(latents * temperature, latent_mask_input,incontext_latents, incontext_length, t_span, additional_model_input,attention_mask, guidance_scale)
649
-
650
- latents[:,0:incontext_length,:] = incontext_latents[:,0:incontext_length,:]
651
- latents = latents.permute(0,2,1).contiguous()
652
- latents = self.normfeat.return_sample(latents)
653
- # latents = latents.permute(0,2,1).contiguous()
654
- return latents
655
-
656
- @torch.no_grad()
657
- def inference(self, input_audios_vocal,input_audios_bgm, lyric, true_latents, latent_length, additional_feats, guidance_scale=2, num_steps=20,
658
- disable_progress=True,layer_vocal=7,layer_bgm=3,scenario='start_seg'):
659
- codes, embeds, spk_embeds = self.fetch_codes(input_audios_vocal,input_audios_bgm, additional_feats,layer_vocal,layer_bgm)
660
-
661
- latents = self.inference_codes(codes, spk_embeds, true_latents, latent_length, additional_feats, \
662
- guidance_scale=guidance_scale, num_steps=num_steps, \
663
- disable_progress=disable_progress,scenario=scenario)
664
- return latents
665
-
666
- def prepare_latents(self, batch_size, num_frames, num_channels_latents, dtype, device):
667
- divisor = 4
668
- shape = (batch_size, num_channels_latents, num_frames, 32)
669
- if(num_frames%divisor>0):
670
- num_frames = round(num_frames/float(divisor))*divisor
671
- shape = (batch_size, num_channels_latents, num_frames, 32)
672
- latents = randn_tensor(shape, generator=None, device=device, dtype=dtype)
673
- return latents
674
-
675
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models/attention.py DELETED
@@ -1,682 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import Any, Dict, Optional
15
-
16
- import torch
17
- import torch.nn.functional as F
18
- from torch import nn
19
-
20
- from diffusers.utils import USE_PEFT_BACKEND
21
- from diffusers.utils.torch_utils import maybe_allow_in_graph
22
- from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
23
- from diffusers.models.attention_processor import Attention
24
- from diffusers.models.embeddings import SinusoidalPositionalEmbedding
25
- from diffusers.models.lora import LoRACompatibleLinear
26
- from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
27
-
28
-
29
- def _chunked_feed_forward(
30
- ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None
31
- ):
32
- # "feed_forward_chunk_size" can be used to save memory
33
- if hidden_states.shape[chunk_dim] % chunk_size != 0:
34
- raise ValueError(
35
- f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
36
- )
37
-
38
- num_chunks = hidden_states.shape[chunk_dim] // chunk_size
39
- if lora_scale is None:
40
- ff_output = torch.cat(
41
- [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
42
- dim=chunk_dim,
43
- )
44
- else:
45
- # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete
46
- ff_output = torch.cat(
47
- [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
48
- dim=chunk_dim,
49
- )
50
-
51
- return ff_output
52
-
53
-
54
- @maybe_allow_in_graph
55
- class GatedSelfAttentionDense(nn.Module):
56
- r"""
57
- A gated self-attention dense layer that combines visual features and object features.
58
-
59
- Parameters:
60
- query_dim (`int`): The number of channels in the query.
61
- context_dim (`int`): The number of channels in the context.
62
- n_heads (`int`): The number of heads to use for attention.
63
- d_head (`int`): The number of channels in each head.
64
- """
65
-
66
- def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
67
- super().__init__()
68
-
69
- # we need a linear projection since we need cat visual feature and obj feature
70
- self.linear = nn.Linear(context_dim, query_dim)
71
-
72
- self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
73
- self.ff = FeedForward(query_dim, activation_fn="geglu")
74
-
75
- self.norm1 = nn.LayerNorm(query_dim)
76
- self.norm2 = nn.LayerNorm(query_dim)
77
-
78
- self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
79
- self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
80
-
81
- self.enabled = True
82
-
83
- def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
84
- if not self.enabled:
85
- return x
86
-
87
- n_visual = x.shape[1]
88
- objs = self.linear(objs)
89
-
90
- x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
91
- x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
92
-
93
- return x
94
-
95
-
96
- @maybe_allow_in_graph
97
- class BasicTransformerBlock(nn.Module):
98
- r"""
99
- A basic Transformer block.
100
-
101
- Parameters:
102
- dim (`int`): The number of channels in the input and output.
103
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
104
- attention_head_dim (`int`): The number of channels in each head.
105
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
106
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
107
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
108
- num_embeds_ada_norm (:
109
- obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
110
- attention_bias (:
111
- obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
112
- only_cross_attention (`bool`, *optional*):
113
- Whether to use only cross-attention layers. In this case two cross attention layers are used.
114
- double_self_attention (`bool`, *optional*):
115
- Whether to use two self-attention layers. In this case no cross attention layers are used.
116
- upcast_attention (`bool`, *optional*):
117
- Whether to upcast the attention computation to float32. This is useful for mixed precision training.
118
- norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
119
- Whether to use learnable elementwise affine parameters for normalization.
120
- norm_type (`str`, *optional*, defaults to `"layer_norm"`):
121
- The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
122
- final_dropout (`bool` *optional*, defaults to False):
123
- Whether to apply a final dropout after the last feed-forward layer.
124
- attention_type (`str`, *optional*, defaults to `"default"`):
125
- The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
126
- positional_embeddings (`str`, *optional*, defaults to `None`):
127
- The type of positional embeddings to apply to.
128
- num_positional_embeddings (`int`, *optional*, defaults to `None`):
129
- The maximum number of positional embeddings to apply.
130
- """
131
-
132
- def __init__(
133
- self,
134
- dim: int,
135
- num_attention_heads: int,
136
- attention_head_dim: int,
137
- dropout=0.0,
138
- cross_attention_dim: Optional[int] = None,
139
- activation_fn: str = "geglu",
140
- num_embeds_ada_norm: Optional[int] = None,
141
- attention_bias: bool = False,
142
- only_cross_attention: bool = False,
143
- double_self_attention: bool = False,
144
- upcast_attention: bool = False,
145
- norm_elementwise_affine: bool = True,
146
- norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single'
147
- norm_eps: float = 1e-5,
148
- final_dropout: bool = False,
149
- attention_type: str = "default",
150
- positional_embeddings: Optional[str] = None,
151
- num_positional_embeddings: Optional[int] = None,
152
- ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
153
- ada_norm_bias: Optional[int] = None,
154
- ff_inner_dim: Optional[int] = None,
155
- ff_bias: bool = True,
156
- attention_out_bias: bool = True,
157
- ):
158
- super().__init__()
159
- self.only_cross_attention = only_cross_attention
160
-
161
- self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
162
- self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
163
- self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
164
- self.use_layer_norm = norm_type == "layer_norm"
165
- self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
166
-
167
- if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
168
- raise ValueError(
169
- f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
170
- f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
171
- )
172
-
173
- if positional_embeddings and (num_positional_embeddings is None):
174
- raise ValueError(
175
- "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
176
- )
177
-
178
- if positional_embeddings == "sinusoidal":
179
- self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
180
- else:
181
- self.pos_embed = None
182
-
183
- # Define 3 blocks. Each block has its own normalization layer.
184
- # 1. Self-Attn
185
- if self.use_ada_layer_norm:
186
- self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
187
- elif self.use_ada_layer_norm_zero:
188
- self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
189
- elif self.use_ada_layer_norm_continuous:
190
- self.norm1 = AdaLayerNormContinuous(
191
- dim,
192
- ada_norm_continous_conditioning_embedding_dim,
193
- norm_elementwise_affine,
194
- norm_eps,
195
- ada_norm_bias,
196
- "rms_norm",
197
- )
198
- else:
199
- self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
200
-
201
- self.attn1 = Attention(
202
- query_dim=dim,
203
- heads=num_attention_heads,
204
- dim_head=attention_head_dim,
205
- dropout=dropout,
206
- bias=attention_bias,
207
- cross_attention_dim=cross_attention_dim if only_cross_attention else None,
208
- upcast_attention=upcast_attention,
209
- out_bias=attention_out_bias,
210
- )
211
-
212
- # 2. Cross-Attn
213
- if cross_attention_dim is not None or double_self_attention:
214
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
215
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
216
- # the second cross attention block.
217
- if self.use_ada_layer_norm:
218
- self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
219
- elif self.use_ada_layer_norm_continuous:
220
- self.norm2 = AdaLayerNormContinuous(
221
- dim,
222
- ada_norm_continous_conditioning_embedding_dim,
223
- norm_elementwise_affine,
224
- norm_eps,
225
- ada_norm_bias,
226
- "rms_norm",
227
- )
228
- else:
229
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
230
-
231
- self.attn2 = Attention(
232
- query_dim=dim,
233
- cross_attention_dim=cross_attention_dim if not double_self_attention else None,
234
- heads=num_attention_heads,
235
- dim_head=attention_head_dim,
236
- dropout=dropout,
237
- bias=attention_bias,
238
- upcast_attention=upcast_attention,
239
- out_bias=attention_out_bias,
240
- ) # is self-attn if encoder_hidden_states is none
241
- else:
242
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
243
- self.attn2 = None
244
-
245
- # 3. Feed-forward
246
- if self.use_ada_layer_norm_continuous:
247
- self.norm3 = AdaLayerNormContinuous(
248
- dim,
249
- ada_norm_continous_conditioning_embedding_dim,
250
- norm_elementwise_affine,
251
- norm_eps,
252
- ada_norm_bias,
253
- "layer_norm",
254
- )
255
- elif not self.use_ada_layer_norm_single:
256
- self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
257
-
258
- self.ff = FeedForward(
259
- dim,
260
- dropout=dropout,
261
- activation_fn=activation_fn,
262
- final_dropout=final_dropout,
263
- inner_dim=ff_inner_dim,
264
- bias=ff_bias,
265
- )
266
-
267
- # 4. Fuser
268
- if attention_type == "gated" or attention_type == "gated-text-image":
269
- self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
270
-
271
- # 5. Scale-shift for PixArt-Alpha.
272
- if self.use_ada_layer_norm_single:
273
- self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
274
-
275
- # let chunk size default to None
276
- self._chunk_size = None
277
- self._chunk_dim = 0
278
-
279
- def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
280
- # Sets chunk feed-forward
281
- self._chunk_size = chunk_size
282
- self._chunk_dim = dim
283
-
284
- def forward(
285
- self,
286
- hidden_states: torch.FloatTensor,
287
- attention_mask: Optional[torch.FloatTensor] = None,
288
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
289
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
290
- timestep: Optional[torch.LongTensor] = None,
291
- cross_attention_kwargs: Dict[str, Any] = None,
292
- class_labels: Optional[torch.LongTensor] = None,
293
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
294
- ) -> torch.FloatTensor:
295
- # Notice that normalization is always applied before the real computation in the following blocks.
296
- # 0. Self-Attention
297
- batch_size = hidden_states.shape[0]
298
-
299
- if self.use_ada_layer_norm:
300
- norm_hidden_states = self.norm1(hidden_states, timestep)
301
- elif self.use_ada_layer_norm_zero:
302
- norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
303
- hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
304
- )
305
- elif self.use_layer_norm:
306
- norm_hidden_states = self.norm1(hidden_states)
307
- elif self.use_ada_layer_norm_continuous:
308
- norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
309
- elif self.use_ada_layer_norm_single:
310
- # print("Using PixArt-Alpha norm")
311
- # print("time step: ", timestep.shape)
312
- # print("self.scale_shift_table: ", self.scale_shift_table.shape)
313
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
314
- self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
315
- ).chunk(6, dim=1)
316
- norm_hidden_states = self.norm1(hidden_states)
317
- # print("scale_msa: ", scale_msa.shape)
318
- # print("shift_msa: ", shift_msa.shape)
319
- #scale_msa: torch.Size([5, 1, 1152])
320
- #shift_msa: torch.Size([5, 1, 1152])
321
- # exit()
322
- # print("before: ", norm_hidden_states.shape)
323
- #before: torch.Size([5, 3584, 1152])
324
- norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
325
- # print("after: ", norm_hidden_states.shape)
326
- #before: torch.Size([5, 3584, 1152])
327
- # exit()
328
- norm_hidden_states = norm_hidden_states.squeeze(1)
329
- else:
330
- raise ValueError("Incorrect norm used")
331
-
332
- if self.pos_embed is not None:
333
- norm_hidden_states = self.pos_embed(norm_hidden_states)
334
-
335
-
336
- # 1. Retrieve lora scale.
337
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
338
-
339
- # 2. Prepare GLIGEN inputs
340
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
341
- gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
342
-
343
- attn_output = self.attn1(
344
- norm_hidden_states,
345
- encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
346
- attention_mask=attention_mask,
347
- **cross_attention_kwargs,
348
- )
349
- if self.use_ada_layer_norm_zero:
350
- attn_output = gate_msa.unsqueeze(1) * attn_output
351
- elif self.use_ada_layer_norm_single:
352
- attn_output = gate_msa * attn_output
353
-
354
- hidden_states = attn_output + hidden_states
355
- if hidden_states.ndim == 4:
356
- hidden_states = hidden_states.squeeze(1)
357
-
358
- # 2.5 GLIGEN Control
359
- if gligen_kwargs is not None:
360
- hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
361
-
362
- # 3. Cross-Attention
363
- if self.attn2 is not None:
364
- if self.use_ada_layer_norm:
365
- norm_hidden_states = self.norm2(hidden_states, timestep)
366
- elif self.use_ada_layer_norm_zero or self.use_layer_norm:
367
- norm_hidden_states = self.norm2(hidden_states)
368
- elif self.use_ada_layer_norm_single:
369
- # For PixArt norm2 isn't applied here:
370
- # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
371
- norm_hidden_states = hidden_states
372
- elif self.use_ada_layer_norm_continuous:
373
- norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
374
- else:
375
- raise ValueError("Incorrect norm")
376
-
377
- if self.pos_embed is not None and self.use_ada_layer_norm_single is False:
378
- norm_hidden_states = self.pos_embed(norm_hidden_states)
379
-
380
- attn_output = self.attn2(
381
- norm_hidden_states,
382
- encoder_hidden_states=encoder_hidden_states,
383
- attention_mask=encoder_attention_mask,
384
- **cross_attention_kwargs,
385
- )
386
- hidden_states = attn_output + hidden_states
387
-
388
- # 4. Feed-forward
389
- if self.use_ada_layer_norm_continuous:
390
- norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
391
- elif not self.use_ada_layer_norm_single:
392
- norm_hidden_states = self.norm3(hidden_states)
393
-
394
- if self.use_ada_layer_norm_zero:
395
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
396
-
397
- if self.use_ada_layer_norm_single:
398
- norm_hidden_states = self.norm2(hidden_states)
399
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
400
-
401
- if self._chunk_size is not None:
402
- # "feed_forward_chunk_size" can be used to save memory
403
- ff_output = _chunked_feed_forward(
404
- self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale
405
- )
406
- else:
407
- ff_output = self.ff(norm_hidden_states, scale=lora_scale)
408
-
409
- if self.use_ada_layer_norm_zero:
410
- ff_output = gate_mlp.unsqueeze(1) * ff_output
411
- elif self.use_ada_layer_norm_single:
412
- ff_output = gate_mlp * ff_output
413
-
414
- hidden_states = ff_output + hidden_states
415
- if hidden_states.ndim == 4:
416
- hidden_states = hidden_states.squeeze(1)
417
-
418
- return hidden_states
419
-
420
-
421
- @maybe_allow_in_graph
422
- class TemporalBasicTransformerBlock(nn.Module):
423
- r"""
424
- A basic Transformer block for video like data.
425
-
426
- Parameters:
427
- dim (`int`): The number of channels in the input and output.
428
- time_mix_inner_dim (`int`): The number of channels for temporal attention.
429
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
430
- attention_head_dim (`int`): The number of channels in each head.
431
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
432
- """
433
-
434
- def __init__(
435
- self,
436
- dim: int,
437
- time_mix_inner_dim: int,
438
- num_attention_heads: int,
439
- attention_head_dim: int,
440
- cross_attention_dim: Optional[int] = None,
441
- ):
442
- super().__init__()
443
- self.is_res = dim == time_mix_inner_dim
444
-
445
- self.norm_in = nn.LayerNorm(dim)
446
-
447
- # Define 3 blocks. Each block has its own normalization layer.
448
- # 1. Self-Attn
449
- self.norm_in = nn.LayerNorm(dim)
450
- self.ff_in = FeedForward(
451
- dim,
452
- dim_out=time_mix_inner_dim,
453
- activation_fn="geglu",
454
- )
455
-
456
- self.norm1 = nn.LayerNorm(time_mix_inner_dim)
457
- self.attn1 = Attention(
458
- query_dim=time_mix_inner_dim,
459
- heads=num_attention_heads,
460
- dim_head=attention_head_dim,
461
- cross_attention_dim=None,
462
- )
463
-
464
- # 2. Cross-Attn
465
- if cross_attention_dim is not None:
466
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
467
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
468
- # the second cross attention block.
469
- self.norm2 = nn.LayerNorm(time_mix_inner_dim)
470
- self.attn2 = Attention(
471
- query_dim=time_mix_inner_dim,
472
- cross_attention_dim=cross_attention_dim,
473
- heads=num_attention_heads,
474
- dim_head=attention_head_dim,
475
- ) # is self-attn if encoder_hidden_states is none
476
- else:
477
- self.norm2 = None
478
- self.attn2 = None
479
-
480
- # 3. Feed-forward
481
- self.norm3 = nn.LayerNorm(time_mix_inner_dim)
482
- self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu")
483
-
484
- # let chunk size default to None
485
- self._chunk_size = None
486
- self._chunk_dim = None
487
-
488
- def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs):
489
- # Sets chunk feed-forward
490
- self._chunk_size = chunk_size
491
- # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off
492
- self._chunk_dim = 1
493
-
494
- def forward(
495
- self,
496
- hidden_states: torch.FloatTensor,
497
- num_frames: int,
498
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
499
- ) -> torch.FloatTensor:
500
- # Notice that normalization is always applied before the real computation in the following blocks.
501
- # 0. Self-Attention
502
- batch_size = hidden_states.shape[0]
503
-
504
- batch_frames, seq_length, channels = hidden_states.shape
505
- batch_size = batch_frames // num_frames
506
-
507
- hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels)
508
- hidden_states = hidden_states.permute(0, 2, 1, 3)
509
- hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels)
510
-
511
- residual = hidden_states
512
- hidden_states = self.norm_in(hidden_states)
513
-
514
- if self._chunk_size is not None:
515
- hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size)
516
- else:
517
- hidden_states = self.ff_in(hidden_states)
518
-
519
- if self.is_res:
520
- hidden_states = hidden_states + residual
521
-
522
- norm_hidden_states = self.norm1(hidden_states)
523
- attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None)
524
- hidden_states = attn_output + hidden_states
525
-
526
- # 3. Cross-Attention
527
- if self.attn2 is not None:
528
- norm_hidden_states = self.norm2(hidden_states)
529
- attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
530
- hidden_states = attn_output + hidden_states
531
-
532
- # 4. Feed-forward
533
- norm_hidden_states = self.norm3(hidden_states)
534
-
535
- if self._chunk_size is not None:
536
- ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
537
- else:
538
- ff_output = self.ff(norm_hidden_states)
539
-
540
- if self.is_res:
541
- hidden_states = ff_output + hidden_states
542
- else:
543
- hidden_states = ff_output
544
-
545
- hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels)
546
- hidden_states = hidden_states.permute(0, 2, 1, 3)
547
- hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels)
548
-
549
- return hidden_states
550
-
551
-
552
- class SkipFFTransformerBlock(nn.Module):
553
- def __init__(
554
- self,
555
- dim: int,
556
- num_attention_heads: int,
557
- attention_head_dim: int,
558
- kv_input_dim: int,
559
- kv_input_dim_proj_use_bias: bool,
560
- dropout=0.0,
561
- cross_attention_dim: Optional[int] = None,
562
- attention_bias: bool = False,
563
- attention_out_bias: bool = True,
564
- ):
565
- super().__init__()
566
- if kv_input_dim != dim:
567
- self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias)
568
- else:
569
- self.kv_mapper = None
570
-
571
- self.norm1 = RMSNorm(dim, 1e-06)
572
-
573
- self.attn1 = Attention(
574
- query_dim=dim,
575
- heads=num_attention_heads,
576
- dim_head=attention_head_dim,
577
- dropout=dropout,
578
- bias=attention_bias,
579
- cross_attention_dim=cross_attention_dim,
580
- out_bias=attention_out_bias,
581
- )
582
-
583
- self.norm2 = RMSNorm(dim, 1e-06)
584
-
585
- self.attn2 = Attention(
586
- query_dim=dim,
587
- cross_attention_dim=cross_attention_dim,
588
- heads=num_attention_heads,
589
- dim_head=attention_head_dim,
590
- dropout=dropout,
591
- bias=attention_bias,
592
- out_bias=attention_out_bias,
593
- )
594
-
595
- def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs):
596
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
597
-
598
- if self.kv_mapper is not None:
599
- encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states))
600
-
601
- norm_hidden_states = self.norm1(hidden_states)
602
-
603
- attn_output = self.attn1(
604
- norm_hidden_states,
605
- encoder_hidden_states=encoder_hidden_states,
606
- **cross_attention_kwargs,
607
- )
608
-
609
- hidden_states = attn_output + hidden_states
610
-
611
- norm_hidden_states = self.norm2(hidden_states)
612
-
613
- attn_output = self.attn2(
614
- norm_hidden_states,
615
- encoder_hidden_states=encoder_hidden_states,
616
- **cross_attention_kwargs,
617
- )
618
-
619
- hidden_states = attn_output + hidden_states
620
-
621
- return hidden_states
622
-
623
-
624
- class FeedForward(nn.Module):
625
- r"""
626
- A feed-forward layer.
627
-
628
- Parameters:
629
- dim (`int`): The number of channels in the input.
630
- dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
631
- mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
632
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
633
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
634
- final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
635
- bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
636
- """
637
-
638
- def __init__(
639
- self,
640
- dim: int,
641
- dim_out: Optional[int] = None,
642
- mult: int = 4,
643
- dropout: float = 0.0,
644
- activation_fn: str = "geglu",
645
- final_dropout: bool = False,
646
- inner_dim=None,
647
- bias: bool = True,
648
- ):
649
- super().__init__()
650
- if inner_dim is None:
651
- inner_dim = int(dim * mult)
652
- dim_out = dim_out if dim_out is not None else dim
653
- linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
654
-
655
- if activation_fn == "gelu":
656
- act_fn = GELU(dim, inner_dim, bias=bias)
657
- if activation_fn == "gelu-approximate":
658
- act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
659
- elif activation_fn == "geglu":
660
- act_fn = GEGLU(dim, inner_dim, bias=bias)
661
- elif activation_fn == "geglu-approximate":
662
- act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
663
-
664
- self.net = nn.ModuleList([])
665
- # project in
666
- self.net.append(act_fn)
667
- # project dropout
668
- self.net.append(nn.Dropout(dropout))
669
- # project out
670
- self.net.append(linear_cls(inner_dim, dim_out, bias=bias))
671
- # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
672
- if final_dropout:
673
- self.net.append(nn.Dropout(dropout))
674
-
675
- def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
676
- compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear)
677
- for module in self.net:
678
- if isinstance(module, compatible_cls):
679
- hidden_states = module(hidden_states, scale)
680
- else:
681
- hidden_states = module(hidden_states)
682
- return hidden_states
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models/attention_add_rot_emb.py DELETED
@@ -1,734 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import Any, Dict, Optional
15
-
16
- import torch
17
- import torch.nn.functional as F
18
- from torch import nn
19
-
20
- from diffusers.utils import USE_PEFT_BACKEND
21
- from diffusers.utils.torch_utils import maybe_allow_in_graph
22
- from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
23
- from diffusers.models.attention_processor import Attention
24
- from diffusers.models.embeddings import SinusoidalPositionalEmbedding
25
- from diffusers.models.lora import LoRACompatibleLinear
26
- from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
27
-
28
-
29
- def _chunked_feed_forward(
30
- ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None
31
- ):
32
- # "feed_forward_chunk_size" can be used to save memory
33
- if hidden_states.shape[chunk_dim] % chunk_size != 0:
34
- raise ValueError(
35
- f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
36
- )
37
-
38
- num_chunks = hidden_states.shape[chunk_dim] // chunk_size
39
- if lora_scale is None:
40
- ff_output = torch.cat(
41
- [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
42
- dim=chunk_dim,
43
- )
44
- else:
45
- # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete
46
- ff_output = torch.cat(
47
- [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
48
- dim=chunk_dim,
49
- )
50
-
51
- return ff_output
52
-
53
-
54
- @maybe_allow_in_graph
55
- class GatedSelfAttentionDense(nn.Module):
56
- r"""
57
- A gated self-attention dense layer that combines visual features and object features.
58
-
59
- Parameters:
60
- query_dim (`int`): The number of channels in the query.
61
- context_dim (`int`): The number of channels in the context.
62
- n_heads (`int`): The number of heads to use for attention.
63
- d_head (`int`): The number of channels in each head.
64
- """
65
-
66
- def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
67
- super().__init__()
68
-
69
- # we need a linear projection since we need cat visual feature and obj feature
70
- self.linear = nn.Linear(context_dim, query_dim)
71
-
72
- self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
73
- self.ff = FeedForward(query_dim, activation_fn="geglu")
74
-
75
- self.norm1 = nn.LayerNorm(query_dim)
76
- self.norm2 = nn.LayerNorm(query_dim)
77
-
78
- self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
79
- self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
80
-
81
- self.enabled = True
82
-
83
- def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
84
- if not self.enabled:
85
- return x
86
-
87
- n_visual = x.shape[1]
88
- objs = self.linear(objs)
89
-
90
- x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
91
- x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
92
-
93
- return x
94
- def precompute_freqs_cis(dim: int, end: int, constant: float = 10000.0):
95
- '''
96
- 计算cos和sin的值,cos值在实部,sin值在虚部,类似于 cosx+j*sinx
97
- :param dim: q,k,v的最后一维,一般为emb_dim/head_num
98
- :param end: 句长length
99
- :param constant: 这里指10000
100
- :return:
101
- 复数计算 torch.polar(a, t)输出, a*(cos(t)+j*sin(t))
102
- '''
103
- # freqs: 计算 1/(10000^(2i/d) ),将结果作为参数theta
104
- # 形式化为 [theta_0, theta_1, ..., theta_(d/2-1)]
105
- freqs = 1.0 / (constant ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) # [d/2]
106
-
107
- # 计算m
108
- t = torch.arange(end, device=freqs.device) # [length]
109
- # 计算m*theta
110
- freqs = torch.outer(t, freqs).float() # [length, d/2]
111
- # freqs形式化为 [m*theta_0, m*theta_1, ..., m*theta_(d/2-1)],其中 m=0,1,...,length-1
112
-
113
- # 计算cos(m*theta)+j*sin(m*theta)
114
- freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
115
- # freqs_cis: [cos(m*theta_0)+j*sin(m*theta_0), cos(m*theta_1)+j*sin(m*theta_1),), ..., cos(m*theta_(d/2-1))+j*sin(m*theta_(d/2-1))]
116
- # 其中j为虚数单位, m=0,1,...,length-1
117
- return freqs_cis # [length, d/2]
118
-
119
- def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
120
- ndim = x.ndim
121
- assert 0 <= 1 < ndim
122
- assert freqs_cis.shape == (x.shape[1], x.shape[-1])
123
- shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)] # (1, length, 1, d/2)
124
- return freqs_cis.view(*shape) # [1, length, 1, d/2]
125
-
126
- def apply_rotary_emb(xq: torch.Tensor, freqs_cis: torch.Tensor,):
127
- # 先将xq维度变为[bs, length, head, d/2, 2], 利用torch.view_as_complex转变为复数
128
- # xq:[q0, q1, .., q(d-1)] 转变为 xq_: [q0+j*q1, q2+j*q3, ..., q(d-2)+j*q(d-1)]
129
- xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) # [bs, length, head, d/2]
130
-
131
-
132
- freqs_cis = reshape_for_broadcast(freqs_cis, xq_) # [1, length, 1, d/2]
133
- # 下式xq_ * freqs_cis形式化输出,以第一个为例, 如下
134
- # (q0+j*q1)(cos(m*theta_0)+j*sin(m*theta_0)) = q0*cos(m*theta_0)-q1*sin(m*theta_0) + j*(q1*cos(m*theta_0)+q0*sin(m*theta_0))
135
- # 上式的实部为q0*cos(m*theta_0)-q1*sin(m*theta_0),虚部为q1*cos(m*theta_0)+q0*sin(m*theta_0)
136
- # 然后通过torch.view_as_real函数,取出实部和虚部,维度由[bs, length, head, d/2]变为[bs, length, head, d/2, 2],最后一维放实部与虚部
137
- # 最后经flatten函数将维度拉平,即[bs, length, head, d]
138
- # 此时xq_out形式化为 [实部0,虚部0,实部1,虚部1,..., 实部(d/2-1), 虚部(d/2-1)]
139
- xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3) # [bs, length, head, d]
140
-
141
- return xq_out.type_as(xq)
142
-
143
- @maybe_allow_in_graph
144
- class BasicTransformerBlock(nn.Module):
145
- r"""
146
- A basic Transformer block.
147
-
148
- Parameters:
149
- dim (`int`): The number of channels in the input and output.
150
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
151
- attention_head_dim (`int`): The number of channels in each head.
152
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
153
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
154
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
155
- num_embeds_ada_norm (:
156
- obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
157
- attention_bias (:
158
- obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
159
- only_cross_attention (`bool`, *optional*):
160
- Whether to use only cross-attention layers. In this case two cross attention layers are used.
161
- double_self_attention (`bool`, *optional*):
162
- Whether to use two self-attention layers. In this case no cross attention layers are used.
163
- upcast_attention (`bool`, *optional*):
164
- Whether to upcast the attention computation to float32. This is useful for mixed precision training.
165
- norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
166
- Whether to use learnable elementwise affine parameters for normalization.
167
- norm_type (`str`, *optional*, defaults to `"layer_norm"`):
168
- The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
169
- final_dropout (`bool` *optional*, defaults to False):
170
- Whether to apply a final dropout after the last feed-forward layer.
171
- attention_type (`str`, *optional*, defaults to `"default"`):
172
- The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
173
- positional_embeddings (`str`, *optional*, defaults to `None`):
174
- The type of positional embeddings to apply to.
175
- num_positional_embeddings (`int`, *optional*, defaults to `None`):
176
- The maximum number of positional embeddings to apply.
177
- """
178
-
179
- def __init__(
180
- self,
181
- dim: int,
182
- num_attention_heads: int,
183
- attention_head_dim: int,
184
- dropout=0.0,
185
- cross_attention_dim: Optional[int] = None,
186
- activation_fn: str = "geglu",
187
- num_embeds_ada_norm: Optional[int] = None,
188
- attention_bias: bool = False,
189
- only_cross_attention: bool = False,
190
- double_self_attention: bool = False,
191
- upcast_attention: bool = False,
192
- norm_elementwise_affine: bool = True,
193
- norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single'
194
- norm_eps: float = 1e-5,
195
- final_dropout: bool = False,
196
- attention_type: str = "default",
197
- positional_embeddings: Optional[str] = None,
198
- num_positional_embeddings: Optional[int] = None,
199
- ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
200
- ada_norm_bias: Optional[int] = None,
201
- ff_inner_dim: Optional[int] = None,
202
- ff_bias: bool = True,
203
- attention_out_bias: bool = True,
204
- ):
205
- super().__init__()
206
- self.only_cross_attention = only_cross_attention
207
-
208
- self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
209
- self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
210
- self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
211
- self.use_layer_norm = norm_type == "layer_norm"
212
- self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
213
-
214
- if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
215
- raise ValueError(
216
- f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
217
- f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
218
- )
219
-
220
- if positional_embeddings and (num_positional_embeddings is None):
221
- raise ValueError(
222
- "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
223
- )
224
-
225
- if positional_embeddings == "sinusoidal":
226
- self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
227
- else:
228
- self.pos_embed = None
229
-
230
- # Define 3 blocks. Each block has its own normalization layer.
231
- # 1. Self-Attn
232
- if self.use_ada_layer_norm:
233
- self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
234
- elif self.use_ada_layer_norm_zero:
235
- self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
236
- elif self.use_ada_layer_norm_continuous:
237
- self.norm1 = AdaLayerNormContinuous(
238
- dim,
239
- ada_norm_continous_conditioning_embedding_dim,
240
- norm_elementwise_affine,
241
- norm_eps,
242
- ada_norm_bias,
243
- "rms_norm",
244
- )
245
- else:
246
- self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
247
-
248
- self.attn1 = Attention(
249
- query_dim=dim,
250
- heads=num_attention_heads,
251
- dim_head=attention_head_dim,
252
- dropout=dropout,
253
- bias=attention_bias,
254
- cross_attention_dim=cross_attention_dim if only_cross_attention else None,
255
- upcast_attention=upcast_attention,
256
- out_bias=attention_out_bias,
257
- )
258
-
259
- # 2. Cross-Attn
260
- if cross_attention_dim is not None or double_self_attention:
261
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
262
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
263
- # the second cross attention block.
264
- if self.use_ada_layer_norm:
265
- self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
266
- elif self.use_ada_layer_norm_continuous:
267
- self.norm2 = AdaLayerNormContinuous(
268
- dim,
269
- ada_norm_continous_conditioning_embedding_dim,
270
- norm_elementwise_affine,
271
- norm_eps,
272
- ada_norm_bias,
273
- "rms_norm",
274
- )
275
- else:
276
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
277
-
278
- self.attn2 = Attention(
279
- query_dim=dim,
280
- cross_attention_dim=cross_attention_dim if not double_self_attention else None,
281
- heads=num_attention_heads,
282
- dim_head=attention_head_dim,
283
- dropout=dropout,
284
- bias=attention_bias,
285
- upcast_attention=upcast_attention,
286
- out_bias=attention_out_bias,
287
- ) # is self-attn if encoder_hidden_states is none
288
- else:
289
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
290
- self.attn2 = None
291
-
292
- # 3. Feed-forward
293
- if self.use_ada_layer_norm_continuous:
294
- self.norm3 = AdaLayerNormContinuous(
295
- dim,
296
- ada_norm_continous_conditioning_embedding_dim,
297
- norm_elementwise_affine,
298
- norm_eps,
299
- ada_norm_bias,
300
- "layer_norm",
301
- )
302
- elif not self.use_ada_layer_norm_single:
303
- self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
304
-
305
- self.ff = FeedForward(
306
- dim,
307
- dropout=dropout,
308
- activation_fn=activation_fn,
309
- final_dropout=final_dropout,
310
- inner_dim=ff_inner_dim,
311
- bias=ff_bias,
312
- )
313
-
314
- # 4. Fuser
315
- if attention_type == "gated" or attention_type == "gated-text-image":
316
- self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
317
-
318
- # 5. Scale-shift for PixArt-Alpha.
319
- if self.use_ada_layer_norm_single:
320
- self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
321
-
322
- # let chunk size default to None
323
- self._chunk_size = None
324
- self._chunk_dim = 0
325
-
326
- def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
327
- # Sets chunk feed-forward
328
- self._chunk_size = chunk_size
329
- self._chunk_dim = dim
330
-
331
- def forward(
332
- self,
333
- hidden_states: torch.FloatTensor,
334
- attention_mask: Optional[torch.FloatTensor] = None,
335
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
336
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
337
- timestep: Optional[torch.LongTensor] = None,
338
- cross_attention_kwargs: Dict[str, Any] = None,
339
- class_labels: Optional[torch.LongTensor] = None,
340
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
341
- ) -> torch.FloatTensor:
342
- # Notice that normalization is always applied before the real computation in the following blocks.
343
- # 0. Self-Attention
344
- batch_size = hidden_states.shape[0]
345
-
346
- if self.use_ada_layer_norm:
347
- norm_hidden_states = self.norm1(hidden_states, timestep)
348
- elif self.use_ada_layer_norm_zero:
349
- norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
350
- hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
351
- )
352
- elif self.use_layer_norm:
353
- norm_hidden_states = self.norm1(hidden_states)
354
- elif self.use_ada_layer_norm_continuous:
355
- norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
356
- elif self.use_ada_layer_norm_single:
357
- # print("Using PixArt-Alpha norm")
358
- # print("time step: ", timestep.shape)
359
- # print("self.scale_shift_table: ", self.scale_shift_table.shape)
360
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
361
- self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
362
- ).chunk(6, dim=1)
363
- norm_hidden_states = self.norm1(hidden_states)
364
- # print("scale_msa: ", scale_msa.shape)
365
- # print("shift_msa: ", shift_msa.shape)
366
- #scale_msa: torch.Size([5, 1, 1152])
367
- #shift_msa: torch.Size([5, 1, 1152])
368
- # exit()
369
- # print("before: ", norm_hidden_states.shape)
370
- #before: torch.Size([5, 3584, 1152])
371
- norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
372
- # print("after: ", norm_hidden_states.shape)
373
- #before: torch.Size([5, 3584, 1152])
374
- # exit()
375
- norm_hidden_states = norm_hidden_states.squeeze(1)
376
- else:
377
- raise ValueError("Incorrect norm used")
378
-
379
- if self.pos_embed is not None:
380
- norm_hidden_states = self.pos_embed(norm_hidden_states)
381
-
382
- freqs_cis = precompute_freqs_cis(norm_hidden_states.shape[-1], norm_hidden_states.shape[1]).to(norm_hidden_states.device)
383
- print("norm_hidden_states1: ", norm_hidden_states.shape)
384
- norm_hidden_states = apply_rotary_emb(norm_hidden_states, freqs_cis)
385
- print("norm_hidden_states2: ", norm_hidden_states.shape)
386
-
387
-
388
- # 1. Retrieve lora scale.
389
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
390
-
391
- # 2. Prepare GLIGEN inputs
392
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
393
- gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
394
-
395
- attn_output = self.attn1(
396
- norm_hidden_states,
397
- encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
398
- attention_mask=attention_mask,
399
- **cross_attention_kwargs,
400
- )
401
- if self.use_ada_layer_norm_zero:
402
- attn_output = gate_msa.unsqueeze(1) * attn_output
403
- elif self.use_ada_layer_norm_single:
404
- attn_output = gate_msa * attn_output
405
-
406
- hidden_states = attn_output + hidden_states
407
- if hidden_states.ndim == 4:
408
- hidden_states = hidden_states.squeeze(1)
409
-
410
- # 2.5 GLIGEN Control
411
- if gligen_kwargs is not None:
412
- hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
413
-
414
- # 3. Cross-Attention
415
- if self.attn2 is not None:
416
- if self.use_ada_layer_norm:
417
- norm_hidden_states = self.norm2(hidden_states, timestep)
418
- elif self.use_ada_layer_norm_zero or self.use_layer_norm:
419
- norm_hidden_states = self.norm2(hidden_states)
420
- elif self.use_ada_layer_norm_single:
421
- # For PixArt norm2 isn't applied here:
422
- # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
423
- norm_hidden_states = hidden_states
424
- elif self.use_ada_layer_norm_continuous:
425
- norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
426
- else:
427
- raise ValueError("Incorrect norm")
428
-
429
- if self.pos_embed is not None and self.use_ada_layer_norm_single is False:
430
- norm_hidden_states = self.pos_embed(norm_hidden_states)
431
-
432
- attn_output = self.attn2(
433
- norm_hidden_states,
434
- encoder_hidden_states=encoder_hidden_states,
435
- attention_mask=encoder_attention_mask,
436
- **cross_attention_kwargs,
437
- )
438
- hidden_states = attn_output + hidden_states
439
-
440
- # 4. Feed-forward
441
- if self.use_ada_layer_norm_continuous:
442
- norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
443
- elif not self.use_ada_layer_norm_single:
444
- norm_hidden_states = self.norm3(hidden_states)
445
-
446
- if self.use_ada_layer_norm_zero:
447
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
448
-
449
- if self.use_ada_layer_norm_single:
450
- norm_hidden_states = self.norm2(hidden_states)
451
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
452
-
453
- if self._chunk_size is not None:
454
- # "feed_forward_chunk_size" can be used to save memory
455
- ff_output = _chunked_feed_forward(
456
- self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale
457
- )
458
- else:
459
- ff_output = self.ff(norm_hidden_states, scale=lora_scale)
460
-
461
- if self.use_ada_layer_norm_zero:
462
- ff_output = gate_mlp.unsqueeze(1) * ff_output
463
- elif self.use_ada_layer_norm_single:
464
- ff_output = gate_mlp * ff_output
465
-
466
- hidden_states = ff_output + hidden_states
467
- if hidden_states.ndim == 4:
468
- hidden_states = hidden_states.squeeze(1)
469
-
470
- return hidden_states
471
-
472
-
473
- @maybe_allow_in_graph
474
- class TemporalBasicTransformerBlock(nn.Module):
475
- r"""
476
- A basic Transformer block for video like data.
477
-
478
- Parameters:
479
- dim (`int`): The number of channels in the input and output.
480
- time_mix_inner_dim (`int`): The number of channels for temporal attention.
481
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
482
- attention_head_dim (`int`): The number of channels in each head.
483
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
484
- """
485
-
486
- def __init__(
487
- self,
488
- dim: int,
489
- time_mix_inner_dim: int,
490
- num_attention_heads: int,
491
- attention_head_dim: int,
492
- cross_attention_dim: Optional[int] = None,
493
- ):
494
- super().__init__()
495
- self.is_res = dim == time_mix_inner_dim
496
-
497
- self.norm_in = nn.LayerNorm(dim)
498
-
499
- # Define 3 blocks. Each block has its own normalization layer.
500
- # 1. Self-Attn
501
- self.norm_in = nn.LayerNorm(dim)
502
- self.ff_in = FeedForward(
503
- dim,
504
- dim_out=time_mix_inner_dim,
505
- activation_fn="geglu",
506
- )
507
-
508
- self.norm1 = nn.LayerNorm(time_mix_inner_dim)
509
- self.attn1 = Attention(
510
- query_dim=time_mix_inner_dim,
511
- heads=num_attention_heads,
512
- dim_head=attention_head_dim,
513
- cross_attention_dim=None,
514
- )
515
-
516
- # 2. Cross-Attn
517
- if cross_attention_dim is not None:
518
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
519
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
520
- # the second cross attention block.
521
- self.norm2 = nn.LayerNorm(time_mix_inner_dim)
522
- self.attn2 = Attention(
523
- query_dim=time_mix_inner_dim,
524
- cross_attention_dim=cross_attention_dim,
525
- heads=num_attention_heads,
526
- dim_head=attention_head_dim,
527
- ) # is self-attn if encoder_hidden_states is none
528
- else:
529
- self.norm2 = None
530
- self.attn2 = None
531
-
532
- # 3. Feed-forward
533
- self.norm3 = nn.LayerNorm(time_mix_inner_dim)
534
- self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu")
535
-
536
- # let chunk size default to None
537
- self._chunk_size = None
538
- self._chunk_dim = None
539
-
540
- def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs):
541
- # Sets chunk feed-forward
542
- self._chunk_size = chunk_size
543
- # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off
544
- self._chunk_dim = 1
545
-
546
- def forward(
547
- self,
548
- hidden_states: torch.FloatTensor,
549
- num_frames: int,
550
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
551
- ) -> torch.FloatTensor:
552
- # Notice that normalization is always applied before the real computation in the following blocks.
553
- # 0. Self-Attention
554
- batch_size = hidden_states.shape[0]
555
-
556
- batch_frames, seq_length, channels = hidden_states.shape
557
- batch_size = batch_frames // num_frames
558
-
559
- hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels)
560
- hidden_states = hidden_states.permute(0, 2, 1, 3)
561
- hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels)
562
-
563
- residual = hidden_states
564
- hidden_states = self.norm_in(hidden_states)
565
-
566
- if self._chunk_size is not None:
567
- hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size)
568
- else:
569
- hidden_states = self.ff_in(hidden_states)
570
-
571
- if self.is_res:
572
- hidden_states = hidden_states + residual
573
-
574
- norm_hidden_states = self.norm1(hidden_states)
575
- attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None)
576
- hidden_states = attn_output + hidden_states
577
-
578
- # 3. Cross-Attention
579
- if self.attn2 is not None:
580
- norm_hidden_states = self.norm2(hidden_states)
581
- attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
582
- hidden_states = attn_output + hidden_states
583
-
584
- # 4. Feed-forward
585
- norm_hidden_states = self.norm3(hidden_states)
586
-
587
- if self._chunk_size is not None:
588
- ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
589
- else:
590
- ff_output = self.ff(norm_hidden_states)
591
-
592
- if self.is_res:
593
- hidden_states = ff_output + hidden_states
594
- else:
595
- hidden_states = ff_output
596
-
597
- hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels)
598
- hidden_states = hidden_states.permute(0, 2, 1, 3)
599
- hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels)
600
-
601
- return hidden_states
602
-
603
-
604
- class SkipFFTransformerBlock(nn.Module):
605
- def __init__(
606
- self,
607
- dim: int,
608
- num_attention_heads: int,
609
- attention_head_dim: int,
610
- kv_input_dim: int,
611
- kv_input_dim_proj_use_bias: bool,
612
- dropout=0.0,
613
- cross_attention_dim: Optional[int] = None,
614
- attention_bias: bool = False,
615
- attention_out_bias: bool = True,
616
- ):
617
- super().__init__()
618
- if kv_input_dim != dim:
619
- self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias)
620
- else:
621
- self.kv_mapper = None
622
-
623
- self.norm1 = RMSNorm(dim, 1e-06)
624
-
625
- self.attn1 = Attention(
626
- query_dim=dim,
627
- heads=num_attention_heads,
628
- dim_head=attention_head_dim,
629
- dropout=dropout,
630
- bias=attention_bias,
631
- cross_attention_dim=cross_attention_dim,
632
- out_bias=attention_out_bias,
633
- )
634
-
635
- self.norm2 = RMSNorm(dim, 1e-06)
636
-
637
- self.attn2 = Attention(
638
- query_dim=dim,
639
- cross_attention_dim=cross_attention_dim,
640
- heads=num_attention_heads,
641
- dim_head=attention_head_dim,
642
- dropout=dropout,
643
- bias=attention_bias,
644
- out_bias=attention_out_bias,
645
- )
646
-
647
- def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs):
648
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
649
-
650
- if self.kv_mapper is not None:
651
- encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states))
652
-
653
- norm_hidden_states = self.norm1(hidden_states)
654
-
655
- attn_output = self.attn1(
656
- norm_hidden_states,
657
- encoder_hidden_states=encoder_hidden_states,
658
- **cross_attention_kwargs,
659
- )
660
-
661
- hidden_states = attn_output + hidden_states
662
-
663
- norm_hidden_states = self.norm2(hidden_states)
664
-
665
- attn_output = self.attn2(
666
- norm_hidden_states,
667
- encoder_hidden_states=encoder_hidden_states,
668
- **cross_attention_kwargs,
669
- )
670
-
671
- hidden_states = attn_output + hidden_states
672
-
673
- return hidden_states
674
-
675
-
676
- class FeedForward(nn.Module):
677
- r"""
678
- A feed-forward layer.
679
-
680
- Parameters:
681
- dim (`int`): The number of channels in the input.
682
- dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
683
- mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
684
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
685
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
686
- final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
687
- bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
688
- """
689
-
690
- def __init__(
691
- self,
692
- dim: int,
693
- dim_out: Optional[int] = None,
694
- mult: int = 4,
695
- dropout: float = 0.0,
696
- activation_fn: str = "geglu",
697
- final_dropout: bool = False,
698
- inner_dim=None,
699
- bias: bool = True,
700
- ):
701
- super().__init__()
702
- if inner_dim is None:
703
- inner_dim = int(dim * mult)
704
- dim_out = dim_out if dim_out is not None else dim
705
- linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
706
-
707
- if activation_fn == "gelu":
708
- act_fn = GELU(dim, inner_dim, bias=bias)
709
- if activation_fn == "gelu-approximate":
710
- act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
711
- elif activation_fn == "geglu":
712
- act_fn = GEGLU(dim, inner_dim, bias=bias)
713
- elif activation_fn == "geglu-approximate":
714
- act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
715
-
716
- self.net = nn.ModuleList([])
717
- # project in
718
- self.net.append(act_fn)
719
- # project dropout
720
- self.net.append(nn.Dropout(dropout))
721
- # project out
722
- self.net.append(linear_cls(inner_dim, dim_out, bias=bias))
723
- # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
724
- if final_dropout:
725
- self.net.append(nn.Dropout(dropout))
726
-
727
- def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
728
- compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear)
729
- for module in self.net:
730
- if isinstance(module, compatible_cls):
731
- hidden_states = module(hidden_states, scale)
732
- else:
733
- hidden_states = module(hidden_states)
734
- return hidden_states
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models/test_model.py DELETED
@@ -1,92 +0,0 @@
1
- from thop import profile
2
- from thop import clever_format
3
- import torch
4
- from tqdm import tqdm
5
- import time
6
- import sys
7
- sys.path.append('./')
8
-
9
-
10
- def analyze_model(model, inputs):
11
- # model size
12
- num_trainable_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
13
- print("Num trainable parameters: {} M".format(num_trainable_parameters/1000./1000.))
14
-
15
- # computation cost
16
- with torch.no_grad():
17
- model.eval()
18
- macs, params = profile(model, inputs=inputs)
19
- macs, params = clever_format([macs, params], "%.3f")
20
- print("Macs: {}, Params: {}".format(macs, params))
21
-
22
- run_times = 50
23
- # eval forward 100 times
24
- with torch.no_grad():
25
- model = model.eval().to('cuda')
26
- inputs = [i.to('cuda') if isinstance(i, torch.Tensor) else i for i in inputs]
27
- model.init_device_dtype(inputs[0].device, inputs[0].dtype)
28
- st = time.time()
29
- for i in tqdm(range(run_times)):
30
- _ = model(*inputs)
31
- et = time.time()
32
- print("Eval forward : {:.03f} secs/per iter".format((et-st)/float(run_times)))
33
-
34
- # train backward 100 times
35
- model = model.train().to('cuda')
36
- inputs = [i.to('cuda') if isinstance(i, torch.Tensor) else i for i in inputs]
37
- model.init_device_dtype(inputs[0].device, inputs[0].dtype)
38
- optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
39
- optimizer.zero_grad()
40
- st = time.time()
41
- for i in tqdm(range(run_times)):
42
- inputs = [torch.rand_like(i) if isinstance(i, torch.cuda.FloatTensor) else i for i in inputs]
43
- out = model(*inputs)
44
- optimizer.zero_grad()
45
- out.mean().backward()
46
- optimizer.step()
47
- et = time.time()
48
- print("Train forward : {:.03f} secs/per iter".format((et-st)/float(run_times)))
49
-
50
- def fetch_model_v3_transformer():
51
- # num params: 326M
52
- # macs (uncorrect): 261G/iter
53
- # infer: 0.32s/iter
54
- # train: 2.54s/iter
55
- from models_transformercond_winorm_ch16_everything_512 import PromptCondAudioDiffusion
56
- model = PromptCondAudioDiffusion( \
57
- "configs/scheduler/stable_diffusion_2.1_largenoise.json", \
58
- None, \
59
- "configs/models/transformer2D.json"
60
- )
61
- inputs = [
62
- torch.rand(1,16,1024*3//8,32),
63
- torch.rand(1,7,512),
64
- torch.tensor([1,]),
65
- torch.tensor([0,]),
66
- False,
67
- ]
68
- return model, inputs
69
-
70
- def fetch_model_v3_unet():
71
- # num params: 310M
72
- # infer: 0.10s/iter
73
- # train: 0.70s/iter
74
- from models_musicldm_winorm_ch16_everything_sepnorm import PromptCondAudioDiffusion
75
- model = PromptCondAudioDiffusion( \
76
- "configs/scheduler/stable_diffusion_2.1_largenoise.json", \
77
- None, \
78
- "configs/diffusion_clapcond_model_config_ch16_everything.json"
79
- )
80
- inputs = [
81
- torch.rand(1,16,1024*3//8,32),
82
- torch.rand(1,7,512),
83
- torch.tensor([1,]),
84
- torch.tensor([0,]),
85
- False,
86
- ]
87
- return model, inputs
88
-
89
- if __name__=="__main__":
90
- model, inputs = fetch_model_v3_transformer()
91
- # model, inputs = fetch_model_v3_unet()
92
- analyze_model(model, inputs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models/transformer_2d.py DELETED
@@ -1,487 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from dataclasses import dataclass
15
- from typing import Any, Dict, Optional
16
-
17
- import torch
18
- import torch.nn.functional as F
19
- from torch import nn
20
-
21
- from diffusers.configuration_utils import ConfigMixin, register_to_config
22
- from diffusers.models.embeddings import ImagePositionalEmbeddings
23
- from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, is_torch_version
24
- from models.attention import BasicTransformerBlock
25
- from diffusers.models.embeddings import PatchEmbed, PixArtAlphaTextProjection
26
- from diffusers.models.lora import LoRACompatibleConv, LoRACompatibleLinear
27
- from diffusers.models.modeling_utils import ModelMixin
28
- from diffusers.models.normalization import AdaLayerNormSingle
29
-
30
-
31
- @dataclass
32
- class Transformer2DModelOutput(BaseOutput):
33
- """
34
- The output of [`Transformer2DModel`].
35
-
36
- Args:
37
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
38
- The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
39
- distributions for the unnoised latent pixels.
40
- """
41
-
42
- sample: torch.FloatTensor
43
-
44
-
45
- class Transformer2DModel(ModelMixin, ConfigMixin):
46
- """
47
- A 2D Transformer model for image-like data.
48
-
49
- Parameters:
50
- num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
51
- attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
52
- in_channels (`int`, *optional*):
53
- The number of channels in the input and output (specify if the input is **continuous**).
54
- num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
55
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
56
- cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
57
- sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
58
- This is fixed during training since it is used to learn a number of position embeddings.
59
- num_vector_embeds (`int`, *optional*):
60
- The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
61
- Includes the class for the masked latent pixel.
62
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
63
- num_embeds_ada_norm ( `int`, *optional*):
64
- The number of diffusion steps used during training. Pass if at least one of the norm_layers is
65
- `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
66
- added to the hidden states.
67
-
68
- During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
69
- attention_bias (`bool`, *optional*):
70
- Configure if the `TransformerBlocks` attention should contain a bias parameter.
71
- """
72
-
73
- _supports_gradient_checkpointing = True
74
-
75
- @register_to_config
76
- def __init__(
77
- self,
78
- num_attention_heads: int = 16,
79
- attention_head_dim: int = 88,
80
- in_channels: Optional[int] = None,
81
- out_channels: Optional[int] = None,
82
- num_layers: int = 1,
83
- dropout: float = 0.0,
84
- norm_num_groups: int = 32,
85
- cross_attention_dim: Optional[int] = None,
86
- attention_bias: bool = False,
87
- sample_size: Optional[int] = None,
88
- num_vector_embeds: Optional[int] = None,
89
- patch_size: Optional[int] = None,
90
- activation_fn: str = "geglu",
91
- num_embeds_ada_norm: Optional[int] = None,
92
- use_linear_projection: bool = False,
93
- only_cross_attention: bool = False,
94
- double_self_attention: bool = False,
95
- upcast_attention: bool = False,
96
- norm_type: str = "layer_norm",
97
- norm_elementwise_affine: bool = True,
98
- norm_eps: float = 1e-5,
99
- attention_type: str = "default",
100
- caption_channels: int = None,
101
- ):
102
- super().__init__()
103
- self.use_linear_projection = use_linear_projection
104
- self.num_attention_heads = num_attention_heads
105
- self.attention_head_dim = attention_head_dim
106
- inner_dim = num_attention_heads * attention_head_dim
107
-
108
- conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
109
- linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
110
-
111
- # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
112
- # Define whether input is continuous or discrete depending on configuration
113
- self.is_input_continuous = (in_channels is not None) and (patch_size is None)
114
- self.is_input_vectorized = num_vector_embeds is not None
115
- self.is_input_patches = in_channels is not None and patch_size is not None
116
-
117
- if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
118
- deprecation_message = (
119
- f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
120
- " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."
121
- " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
122
- " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
123
- " would be very nice if you could open a Pull request for the `transformer/config.json` file"
124
- )
125
- deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
126
- norm_type = "ada_norm"
127
-
128
- if self.is_input_continuous and self.is_input_vectorized:
129
- raise ValueError(
130
- f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
131
- " sure that either `in_channels` or `num_vector_embeds` is None."
132
- )
133
- elif self.is_input_vectorized and self.is_input_patches:
134
- raise ValueError(
135
- f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
136
- " sure that either `num_vector_embeds` or `num_patches` is None."
137
- )
138
- elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
139
- raise ValueError(
140
- f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
141
- f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
142
- )
143
-
144
- # 2. Define input layers
145
- if self.is_input_continuous:
146
- self.in_channels = in_channels
147
-
148
- self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
149
- if use_linear_projection:
150
- self.proj_in = linear_cls(in_channels, inner_dim)
151
- else:
152
- self.proj_in = conv_cls(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
153
- elif self.is_input_vectorized:
154
- assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
155
- assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"
156
-
157
- self.height = sample_size
158
- self.width = sample_size
159
- self.num_vector_embeds = num_vector_embeds
160
- self.num_latent_pixels = self.height * self.width
161
-
162
- self.latent_image_embedding = ImagePositionalEmbeddings(
163
- num_embed=num_vector_embeds, embed_dim=inner_dim, height=self.height, width=self.width
164
- )
165
- elif self.is_input_patches:
166
- assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"
167
-
168
- self.height = sample_size
169
- self.width = sample_size
170
-
171
- self.patch_size = patch_size
172
- interpolation_scale = self.config.sample_size // 64 # => 64 (= 512 pixart) has interpolation scale 1
173
- interpolation_scale = max(interpolation_scale, 1)
174
- self.pos_embed = PatchEmbed(
175
- height=sample_size,
176
- width=sample_size,
177
- patch_size=patch_size,
178
- in_channels=in_channels,
179
- embed_dim=inner_dim,
180
- interpolation_scale=interpolation_scale,
181
- )
182
-
183
- # 3. Define transformers blocks
184
- self.transformer_blocks = nn.ModuleList(
185
- [
186
- BasicTransformerBlock(
187
- inner_dim,
188
- num_attention_heads,
189
- attention_head_dim,
190
- dropout=dropout,
191
- cross_attention_dim=cross_attention_dim,
192
- activation_fn=activation_fn,
193
- num_embeds_ada_norm=num_embeds_ada_norm,
194
- attention_bias=attention_bias,
195
- only_cross_attention=only_cross_attention,
196
- double_self_attention=double_self_attention,
197
- upcast_attention=upcast_attention,
198
- norm_type=norm_type,
199
- norm_elementwise_affine=norm_elementwise_affine,
200
- norm_eps=norm_eps,
201
- attention_type=attention_type,
202
- )
203
- for d in range(num_layers)
204
- ]
205
- )
206
-
207
- # 4. Define output layers
208
- self.out_channels = in_channels if out_channels is None else out_channels
209
- if self.is_input_continuous:
210
- # TODO: should use out_channels for continuous projections
211
- if use_linear_projection:
212
- self.proj_out = linear_cls(inner_dim, in_channels)
213
- else:
214
- self.proj_out = conv_cls(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
215
- elif self.is_input_vectorized:
216
- self.norm_out = nn.LayerNorm(inner_dim)
217
- self.out = nn.Linear(inner_dim, self.num_vector_embeds - 1)
218
- elif self.is_input_patches and norm_type != "ada_norm_single":
219
- self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
220
- self.proj_out_1 = nn.Linear(inner_dim, 2 * inner_dim)
221
- self.proj_out_2 = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
222
- elif self.is_input_patches and norm_type == "ada_norm_single":
223
- self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
224
- self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5)
225
- self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
226
-
227
- # 5. PixArt-Alpha blocks.
228
- self.adaln_single = None
229
- self.use_additional_conditions = False
230
- if norm_type == "ada_norm_single":
231
- self.use_additional_conditions = self.config.sample_size == 128
232
- # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
233
- # additional conditions until we find better name
234
- self.adaln_single = AdaLayerNormSingle(inner_dim, use_additional_conditions=self.use_additional_conditions)
235
-
236
- self.caption_projection = None
237
- if caption_channels is not None:
238
- self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
239
-
240
- self.gradient_checkpointing = False
241
-
242
- def _set_gradient_checkpointing(self, module, value=False):
243
- if hasattr(module, "gradient_checkpointing"):
244
- module.gradient_checkpointing = value
245
-
246
- def forward(
247
- self,
248
- hidden_states: torch.Tensor,
249
- encoder_hidden_states: Optional[torch.Tensor] = None,
250
- timestep: Optional[torch.LongTensor] = None,
251
- added_cond_kwargs: Dict[str, torch.Tensor] = None,
252
- class_labels: Optional[torch.LongTensor] = None,
253
- cross_attention_kwargs: Dict[str, Any] = None,
254
- attention_mask: Optional[torch.Tensor] = None,
255
- encoder_attention_mask: Optional[torch.Tensor] = None,
256
- return_dict: bool = True,
257
- ):
258
- """
259
- The [`Transformer2DModel`] forward method.
260
-
261
- Args:
262
- hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
263
- Input `hidden_states`.
264
- encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
265
- Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
266
- self-attention.
267
- timestep ( `torch.LongTensor`, *optional*):
268
- Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
269
- class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
270
- Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
271
- `AdaLayerZeroNorm`.
272
- cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
273
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
274
- `self.processor` in
275
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
276
- attention_mask ( `torch.Tensor`, *optional*):
277
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
278
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
279
- negative values to the attention scores corresponding to "discard" tokens.
280
- encoder_attention_mask ( `torch.Tensor`, *optional*):
281
- Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
282
-
283
- * Mask `(batch, sequence_length)` True = keep, False = discard.
284
- * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
285
-
286
- If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
287
- above. This bias will be added to the cross-attention scores.
288
- return_dict (`bool`, *optional*, defaults to `True`):
289
- Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
290
- tuple.
291
-
292
- Returns:
293
- If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
294
- `tuple` where the first element is the sample tensor.
295
- """
296
- # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
297
- # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
298
- # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
299
- # expects mask of shape:
300
- # [batch, key_tokens]
301
- # adds singleton query_tokens dimension:
302
- # [batch, 1, key_tokens]
303
- # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
304
- # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
305
- # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
306
- if attention_mask is not None and attention_mask.ndim == 2:
307
- # assume that mask is expressed as:
308
- # (1 = keep, 0 = discard)
309
- # convert mask into a bias that can be added to attention scores:
310
- # (keep = +0, discard = -10000.0)
311
- attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
312
- attention_mask = attention_mask.unsqueeze(1)
313
-
314
- # convert encoder_attention_mask to a bias the same way we do for attention_mask
315
- if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
316
- encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
317
- encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
318
-
319
- # Retrieve lora scale.
320
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
321
-
322
- # 1. Input
323
- print("before input hidden_states.shape", hidden_states.shape)
324
- # print("is_input_patches", self.is_input_patches)
325
- #true
326
- # print("is_input_vectorized", self.is_input_vectorized)
327
- # print("is_input_continuous", self.is_input_continuous)
328
- #false
329
- # print("use_linear_projection", self.use_linear_projection)
330
- #false
331
- if self.is_input_continuous:
332
- batch, _, height, width = hidden_states.shape
333
- residual = hidden_states
334
-
335
- hidden_states = self.norm(hidden_states)
336
- if not self.use_linear_projection:
337
- hidden_states = (
338
- self.proj_in(hidden_states, scale=lora_scale)
339
- if not USE_PEFT_BACKEND
340
- else self.proj_in(hidden_states)
341
- )
342
- # print("input 1 hidden_states.shape", hidden_states.shape)
343
- inner_dim = hidden_states.shape[1]
344
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
345
- # print("input 2 hidden_states.shape", hidden_states.shape)
346
- else:
347
- inner_dim = hidden_states.shape[1]
348
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
349
- hidden_states = (
350
- self.proj_in(hidden_states, scale=lora_scale)
351
- if not USE_PEFT_BACKEND
352
- else self.proj_in(hidden_states)
353
- )
354
-
355
- elif self.is_input_vectorized:
356
- hidden_states = self.latent_image_embedding(hidden_states)
357
- elif self.is_input_patches:
358
- height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
359
- # print("before patches hidden_states.shape", hidden_states.shape)
360
- hidden_states = self.pos_embed(hidden_states)
361
- # print("after patches hidden_states.shape", hidden_states.shape)
362
-
363
- if self.adaln_single is not None:
364
- if self.use_additional_conditions and added_cond_kwargs is None:
365
- raise ValueError(
366
- "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
367
- )
368
- batch_size = hidden_states.shape[0]
369
- print("time step before adaln_single", timestep)
370
- timestep, embedded_timestep = self.adaln_single(
371
- timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
372
- )
373
- print("time step after adaln_single", timestep.shape)
374
- print("embedded_timestep after adaln_single", embedded_timestep.shape)
375
-
376
-
377
- # 2. Blocks
378
- print("before blocks hidden_states.shape", hidden_states.shape)
379
- if self.caption_projection is not None:
380
- batch_size = hidden_states.shape[0]
381
- encoder_hidden_states = self.caption_projection(encoder_hidden_states)
382
- encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
383
-
384
- for block in self.transformer_blocks:
385
- if self.training and self.gradient_checkpointing:
386
-
387
- def create_custom_forward(module, return_dict=None):
388
- def custom_forward(*inputs):
389
- if return_dict is not None:
390
- return module(*inputs, return_dict=return_dict)
391
- else:
392
- return module(*inputs)
393
-
394
- return custom_forward
395
-
396
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
397
- hidden_states = torch.utils.checkpoint.checkpoint(
398
- create_custom_forward(block),
399
- hidden_states,
400
- attention_mask,
401
- encoder_hidden_states,
402
- encoder_attention_mask,
403
- timestep,
404
- cross_attention_kwargs,
405
- class_labels,
406
- **ckpt_kwargs,
407
- )
408
- else:
409
- hidden_states = block(
410
- hidden_states,
411
- attention_mask=attention_mask,
412
- encoder_hidden_states=encoder_hidden_states,
413
- encoder_attention_mask=encoder_attention_mask,
414
- timestep=timestep,
415
- cross_attention_kwargs=cross_attention_kwargs,
416
- class_labels=class_labels,
417
- )
418
-
419
-
420
- # 3. Output
421
- print("after blocks hidden_states.shape", hidden_states.shape)
422
- if self.is_input_continuous:
423
- print("1")
424
- if not self.use_linear_projection:
425
- print("1 hidden_states.shape", hidden_states.shape)
426
- hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
427
- hidden_states = (
428
- self.proj_out(hidden_states, scale=lora_scale)
429
- if not USE_PEFT_BACKEND
430
- else self.proj_out(hidden_states)
431
- )
432
- print("2 hidden_states.shape", hidden_states.shape)
433
- else:
434
- hidden_states = (
435
- self.proj_out(hidden_states, scale=lora_scale)
436
- if not USE_PEFT_BACKEND
437
- else self.proj_out(hidden_states)
438
- )
439
- hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
440
-
441
- output = hidden_states + residual
442
- elif self.is_input_vectorized:
443
- print("2")
444
- hidden_states = self.norm_out(hidden_states)
445
- logits = self.out(hidden_states)
446
- # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
447
- logits = logits.permute(0, 2, 1)
448
-
449
- # log(p(x_0))
450
- output = F.log_softmax(logits.double(), dim=1).float()
451
-
452
- if self.is_input_patches:
453
- print("3")
454
- if self.config.norm_type != "ada_norm_single":
455
- conditioning = self.transformer_blocks[0].norm1.emb(
456
- timestep, class_labels, hidden_dtype=hidden_states.dtype
457
- )
458
- shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
459
- hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
460
- hidden_states = self.proj_out_2(hidden_states)
461
- elif self.config.norm_type == "ada_norm_single":
462
- shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
463
- hidden_states = self.norm_out(hidden_states)
464
- # Modulation
465
- hidden_states = hidden_states * (1 + scale) + shift
466
- print("before proj_out hidden_states.shape", hidden_states.shape)
467
- hidden_states = self.proj_out(hidden_states)
468
- print("after proj_out hidden_states.shape", hidden_states.shape)
469
-
470
- hidden_states = hidden_states.squeeze(1)
471
-
472
- # unpatchify
473
- if self.adaln_single is None:
474
- print("4")
475
- height = width = int(hidden_states.shape[1] ** 0.5)
476
- hidden_states = hidden_states.reshape(
477
- shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
478
- )
479
- hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
480
- output = hidden_states.reshape(
481
- shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
482
- )
483
-
484
- if not return_dict:
485
- return (output,)
486
-
487
- return Transformer2DModelOutput(sample=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models/transformer_2d_additionalemb.py DELETED
@@ -1,468 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from dataclasses import dataclass
15
- from typing import Any, Dict, Optional
16
-
17
- import torch
18
- import torch.nn.functional as F
19
- from torch import nn
20
-
21
- from diffusers.configuration_utils import ConfigMixin, register_to_config
22
- from diffusers.models.embeddings import ImagePositionalEmbeddings
23
- from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, is_torch_version
24
- from models.attention import BasicTransformerBlock
25
- from diffusers.models.embeddings import PatchEmbed, PixArtAlphaTextProjection
26
- from diffusers.models.lora import LoRACompatibleConv, LoRACompatibleLinear
27
- from diffusers.models.modeling_utils import ModelMixin
28
- from diffusers.models.normalization import AdaLayerNormSingle
29
-
30
-
31
- @dataclass
32
- class Transformer2DModelOutput(BaseOutput):
33
- """
34
- The output of [`Transformer2DModel`].
35
-
36
- Args:
37
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
38
- The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
39
- distributions for the unnoised latent pixels.
40
- """
41
-
42
- sample: torch.FloatTensor
43
-
44
-
45
- class Transformer2DModel(ModelMixin, ConfigMixin):
46
- """
47
- A 2D Transformer model for image-like data.
48
-
49
- Parameters:
50
- num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
51
- attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
52
- in_channels (`int`, *optional*):
53
- The number of channels in the input and output (specify if the input is **continuous**).
54
- num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
55
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
56
- cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
57
- sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
58
- This is fixed during training since it is used to learn a number of position embeddings.
59
- num_vector_embeds (`int`, *optional*):
60
- The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
61
- Includes the class for the masked latent pixel.
62
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
63
- num_embeds_ada_norm ( `int`, *optional*):
64
- The number of diffusion steps used during training. Pass if at least one of the norm_layers is
65
- `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
66
- added to the hidden states.
67
-
68
- During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
69
- attention_bias (`bool`, *optional*):
70
- Configure if the `TransformerBlocks` attention should contain a bias parameter.
71
- """
72
-
73
- _supports_gradient_checkpointing = True
74
-
75
- @register_to_config
76
- def __init__(
77
- self,
78
- num_attention_heads: int = 16,
79
- attention_head_dim: int = 88,
80
- in_channels: Optional[int] = None,
81
- out_channels: Optional[int] = None,
82
- num_layers: int = 1,
83
- dropout: float = 0.0,
84
- norm_num_groups: int = 32,
85
- cross_attention_dim: Optional[int] = None,
86
- attention_bias: bool = False,
87
- sample_size: Optional[int] = None,
88
- num_vector_embeds: Optional[int] = None,
89
- patch_size: Optional[int] = None,
90
- activation_fn: str = "geglu",
91
- num_embeds_ada_norm: Optional[int] = None,
92
- use_linear_projection: bool = False,
93
- only_cross_attention: bool = False,
94
- double_self_attention: bool = False,
95
- upcast_attention: bool = False,
96
- norm_type: str = "layer_norm",
97
- norm_elementwise_affine: bool = True,
98
- norm_eps: float = 1e-5,
99
- attention_type: str = "default",
100
- caption_channels: int = None,
101
- ):
102
- super().__init__()
103
- self.use_linear_projection = use_linear_projection
104
- self.num_attention_heads = num_attention_heads
105
- self.attention_head_dim = attention_head_dim
106
- inner_dim = num_attention_heads * attention_head_dim
107
-
108
- conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
109
- linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
110
-
111
- # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
112
- # Define whether input is continuous or discrete depending on configuration
113
- self.is_input_continuous = (in_channels is not None) and (patch_size is None)
114
- self.is_input_vectorized = num_vector_embeds is not None
115
- self.is_input_patches = in_channels is not None and patch_size is not None
116
-
117
- if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
118
- deprecation_message = (
119
- f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
120
- " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."
121
- " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
122
- " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
123
- " would be very nice if you could open a Pull request for the `transformer/config.json` file"
124
- )
125
- deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
126
- norm_type = "ada_norm"
127
-
128
- if self.is_input_continuous and self.is_input_vectorized:
129
- raise ValueError(
130
- f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
131
- " sure that either `in_channels` or `num_vector_embeds` is None."
132
- )
133
- elif self.is_input_vectorized and self.is_input_patches:
134
- raise ValueError(
135
- f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
136
- " sure that either `num_vector_embeds` or `num_patches` is None."
137
- )
138
- elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
139
- raise ValueError(
140
- f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
141
- f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
142
- )
143
-
144
- # 2. Define input layers
145
- if self.is_input_continuous:
146
- self.in_channels = in_channels
147
-
148
- self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
149
- if use_linear_projection:
150
- self.proj_in = linear_cls(in_channels, inner_dim)
151
- else:
152
- self.proj_in = conv_cls(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
153
- elif self.is_input_vectorized:
154
- assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
155
- assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"
156
-
157
- self.height = sample_size
158
- self.width = sample_size
159
- self.num_vector_embeds = num_vector_embeds
160
- self.num_latent_pixels = self.height * self.width
161
-
162
- self.latent_image_embedding = ImagePositionalEmbeddings(
163
- num_embed=num_vector_embeds, embed_dim=inner_dim, height=self.height, width=self.width
164
- )
165
- elif self.is_input_patches:
166
- assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"
167
-
168
- self.height = sample_size
169
- self.width = sample_size
170
-
171
- self.patch_size = patch_size
172
- interpolation_scale = self.config.sample_size // 64 # => 64 (= 512 pixart) has interpolation scale 1
173
- interpolation_scale = max(interpolation_scale, 1)
174
- self.pos_embed = PatchEmbed(
175
- height=sample_size,
176
- width=sample_size,
177
- patch_size=patch_size,
178
- in_channels=in_channels,
179
- embed_dim=inner_dim,
180
- interpolation_scale=interpolation_scale,
181
- )
182
-
183
- # 3. Define transformers blocks
184
- self.transformer_blocks = nn.ModuleList(
185
- [
186
- BasicTransformerBlock(
187
- inner_dim,
188
- num_attention_heads,
189
- attention_head_dim,
190
- dropout=dropout,
191
- cross_attention_dim=cross_attention_dim,
192
- activation_fn=activation_fn,
193
- num_embeds_ada_norm=num_embeds_ada_norm,
194
- attention_bias=attention_bias,
195
- only_cross_attention=only_cross_attention,
196
- double_self_attention=double_self_attention,
197
- upcast_attention=upcast_attention,
198
- norm_type=norm_type,
199
- norm_elementwise_affine=norm_elementwise_affine,
200
- norm_eps=norm_eps,
201
- attention_type=attention_type,
202
- )
203
- for d in range(num_layers)
204
- ]
205
- )
206
-
207
- # 4. Define output layers
208
- self.out_channels = in_channels if out_channels is None else out_channels
209
- if self.is_input_continuous:
210
- # TODO: should use out_channels for continuous projections
211
- if use_linear_projection:
212
- self.proj_out = linear_cls(inner_dim, in_channels)
213
- else:
214
- self.proj_out = conv_cls(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
215
- elif self.is_input_vectorized:
216
- self.norm_out = nn.LayerNorm(inner_dim)
217
- self.out = nn.Linear(inner_dim, self.num_vector_embeds - 1)
218
- elif self.is_input_patches and norm_type != "ada_norm_single":
219
- self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
220
- self.proj_out_1 = nn.Linear(inner_dim, 2 * inner_dim)
221
- self.proj_out_2 = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
222
- elif self.is_input_patches and norm_type == "ada_norm_single":
223
- self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
224
- self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5)
225
- self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
226
-
227
- # 5. PixArt-Alpha blocks.
228
- self.adaln_single = None
229
- self.use_additional_conditions = False
230
- if norm_type == "ada_norm_single":
231
- self.use_additional_conditions = self.config.sample_size == 128
232
- # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
233
- # additional conditions until we find better name
234
- self.adaln_single = AdaLayerNormSingle(inner_dim, use_additional_conditions=self.use_additional_conditions)
235
- self.timestep_linear = nn.Sequential(
236
- nn.Linear(inner_dim * 2, inner_dim),
237
- nn.SiLU(),
238
- nn.Linear(inner_dim, 6 * inner_dim),
239
- )
240
- self.embedded_timestep_linear = nn.Linear(inner_dim * 2, inner_dim)
241
-
242
- self.caption_projection = None
243
- if caption_channels is not None:
244
- self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
245
-
246
- self.gradient_checkpointing = False
247
-
248
- def _set_gradient_checkpointing(self, module, value=False):
249
- if hasattr(module, "gradient_checkpointing"):
250
- module.gradient_checkpointing = value
251
-
252
- def forward(
253
- self,
254
- hidden_states: torch.Tensor,
255
- additional_embd: torch.Tensor,
256
- encoder_hidden_states: Optional[torch.Tensor] = None,
257
- timestep: Optional[torch.LongTensor] = None,
258
- added_cond_kwargs: Dict[str, torch.Tensor] = None,
259
- class_labels: Optional[torch.LongTensor] = None,
260
- cross_attention_kwargs: Dict[str, Any] = None,
261
- attention_mask: Optional[torch.Tensor] = None,
262
- encoder_attention_mask: Optional[torch.Tensor] = None,
263
- return_dict: bool = True,
264
- ):
265
- """
266
- The [`Transformer2DModel`] forward method.
267
-
268
- Args:
269
- hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
270
- Input `hidden_states`.
271
- encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
272
- Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
273
- self-attention.
274
- timestep ( `torch.LongTensor`, *optional*):
275
- Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
276
- class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
277
- Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
278
- `AdaLayerZeroNorm`.
279
- cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
280
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
281
- `self.processor` in
282
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
283
- attention_mask ( `torch.Tensor`, *optional*):
284
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
285
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
286
- negative values to the attention scores corresponding to "discard" tokens.
287
- encoder_attention_mask ( `torch.Tensor`, *optional*):
288
- Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
289
-
290
- * Mask `(batch, sequence_length)` True = keep, False = discard.
291
- * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
292
-
293
- If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
294
- above. This bias will be added to the cross-attention scores.
295
- return_dict (`bool`, *optional*, defaults to `True`):
296
- Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
297
- tuple.
298
-
299
- Returns:
300
- If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
301
- `tuple` where the first element is the sample tensor.
302
- """
303
- # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
304
- # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
305
- # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
306
- # expects mask of shape:
307
- # [batch, key_tokens]
308
- # adds singleton query_tokens dimension:
309
- # [batch, 1, key_tokens]
310
- # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
311
- # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
312
- # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
313
- if attention_mask is not None and attention_mask.ndim == 2:
314
- # assume that mask is expressed as:
315
- # (1 = keep, 0 = discard)
316
- # convert mask into a bias that can be added to attention scores:
317
- # (keep = +0, discard = -10000.0)
318
- attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
319
- attention_mask = attention_mask.unsqueeze(1)
320
-
321
- # convert encoder_attention_mask to a bias the same way we do for attention_mask
322
- if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
323
- encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
324
- encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
325
-
326
- # Retrieve lora scale.
327
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
328
-
329
- # 1. Input
330
- if self.is_input_continuous:
331
- batch, _, height, width = hidden_states.shape
332
- residual = hidden_states
333
-
334
- hidden_states = self.norm(hidden_states)
335
- if not self.use_linear_projection:
336
- hidden_states = (
337
- self.proj_in(hidden_states, scale=lora_scale)
338
- if not USE_PEFT_BACKEND
339
- else self.proj_in(hidden_states)
340
- )
341
- inner_dim = hidden_states.shape[1]
342
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
343
- else:
344
- inner_dim = hidden_states.shape[1]
345
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
346
- hidden_states = (
347
- self.proj_in(hidden_states, scale=lora_scale)
348
- if not USE_PEFT_BACKEND
349
- else self.proj_in(hidden_states)
350
- )
351
-
352
- elif self.is_input_vectorized:
353
- hidden_states = self.latent_image_embedding(hidden_states)
354
- elif self.is_input_patches:
355
- height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
356
- hidden_states = self.pos_embed(hidden_states)
357
-
358
- if self.adaln_single is not None:
359
- if self.use_additional_conditions and added_cond_kwargs is None:
360
- raise ValueError(
361
- "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
362
- )
363
- batch_size = hidden_states.shape[0]
364
- timestep, embedded_timestep = self.adaln_single(
365
- timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
366
- )
367
- timestep = self.timestep_linear(torch.cat([embedded_timestep, additional_embd],1))
368
- embedded_timestep = self.embedded_timestep_linear(torch.cat([embedded_timestep, additional_embd],1))
369
-
370
- # 2. Blocks
371
- if self.caption_projection is not None:
372
- batch_size = hidden_states.shape[0]
373
- encoder_hidden_states = self.caption_projection(encoder_hidden_states)
374
- encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
375
-
376
- for block in self.transformer_blocks:
377
- if self.training and self.gradient_checkpointing:
378
-
379
- def create_custom_forward(module, return_dict=None):
380
- def custom_forward(*inputs):
381
- if return_dict is not None:
382
- return module(*inputs, return_dict=return_dict)
383
- else:
384
- return module(*inputs)
385
-
386
- return custom_forward
387
-
388
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
389
- hidden_states = torch.utils.checkpoint.checkpoint(
390
- create_custom_forward(block),
391
- hidden_states,
392
- attention_mask,
393
- encoder_hidden_states,
394
- encoder_attention_mask,
395
- timestep,
396
- cross_attention_kwargs,
397
- class_labels,
398
- **ckpt_kwargs,
399
- )
400
- else:
401
- hidden_states = block(
402
- hidden_states,
403
- attention_mask=attention_mask,
404
- encoder_hidden_states=encoder_hidden_states,
405
- encoder_attention_mask=encoder_attention_mask,
406
- timestep=timestep,
407
- cross_attention_kwargs=cross_attention_kwargs,
408
- class_labels=class_labels,
409
- )
410
-
411
- # 3. Output
412
- if self.is_input_continuous:
413
- if not self.use_linear_projection:
414
- hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
415
- hidden_states = (
416
- self.proj_out(hidden_states, scale=lora_scale)
417
- if not USE_PEFT_BACKEND
418
- else self.proj_out(hidden_states)
419
- )
420
- else:
421
- hidden_states = (
422
- self.proj_out(hidden_states, scale=lora_scale)
423
- if not USE_PEFT_BACKEND
424
- else self.proj_out(hidden_states)
425
- )
426
- hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
427
-
428
- output = hidden_states + residual
429
- elif self.is_input_vectorized:
430
- hidden_states = self.norm_out(hidden_states)
431
- logits = self.out(hidden_states)
432
- # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
433
- logits = logits.permute(0, 2, 1)
434
-
435
- # log(p(x_0))
436
- output = F.log_softmax(logits.double(), dim=1).float()
437
-
438
- if self.is_input_patches:
439
- if self.config.norm_type != "ada_norm_single":
440
- conditioning = self.transformer_blocks[0].norm1.emb(
441
- timestep, class_labels, hidden_dtype=hidden_states.dtype
442
- )
443
- shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
444
- hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
445
- hidden_states = self.proj_out_2(hidden_states)
446
- elif self.config.norm_type == "ada_norm_single":
447
- shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
448
- hidden_states = self.norm_out(hidden_states)
449
- # Modulation
450
- hidden_states = hidden_states * (1 + scale) + shift
451
- hidden_states = self.proj_out(hidden_states)
452
- hidden_states = hidden_states.squeeze(1)
453
-
454
- # unpatchify
455
- if self.adaln_single is None:
456
- height = width = int(hidden_states.shape[1] ** 0.5)
457
- hidden_states = hidden_states.reshape(
458
- shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
459
- )
460
- hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
461
- output = hidden_states.reshape(
462
- shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
463
- )
464
-
465
- if not return_dict:
466
- return (output,)
467
-
468
- return Transformer2DModelOutput(sample=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models/transformer_2d_flow.py DELETED
@@ -1,545 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from dataclasses import dataclass
15
- import math
16
- from typing import Any, Dict, Optional, Tuple
17
-
18
- import torch
19
- import torch.nn.functional as F
20
- from torch import nn
21
-
22
- from diffusers.configuration_utils import ConfigMixin, register_to_config
23
- from diffusers.models.embeddings import ImagePositionalEmbeddings
24
- from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, is_torch_version
25
- from models.attention import BasicTransformerBlock
26
- from diffusers.models.embeddings import PatchEmbed, PixArtAlphaTextProjection
27
- from diffusers.models.lora import LoRACompatibleConv, LoRACompatibleLinear
28
- from diffusers.models.modeling_utils import ModelMixin
29
- from diffusers.models.embeddings import TimestepEmbedding
30
-
31
- class PixArtAlphaCombinedFlowEmbeddings(nn.Module):
32
- """
33
- For PixArt-Alpha.
34
-
35
- Reference:
36
- https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L164C9-L168C29
37
- """
38
-
39
- def __init__(self, embedding_dim, size_emb_dim, use_additional_conditions: bool = False):
40
- super().__init__()
41
-
42
- self.flow_t_size = 512
43
- self.outdim = size_emb_dim
44
- self.timestep_embedder = TimestepEmbedding(in_channels=self.flow_t_size, time_embed_dim=embedding_dim)
45
-
46
- self.use_additional_conditions = use_additional_conditions
47
- if use_additional_conditions:
48
- self.additional_condition_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
49
- self.resolution_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
50
- self.aspect_ratio_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
51
-
52
- # https://github.com/atong01/conditional-flow-matching/blob/main/torchcfm/models/unet/nn.py#L87
53
- def timestep_embedding(self, timesteps, max_period=10000, scale=1000):
54
- """Create sinusoidal timestep embeddings.
55
-
56
- :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional.
57
- :param dim: the dimension of the output.
58
- :param max_period: controls the minimum frequency of the embeddings.
59
- :return: an [N x dim] Tensor of positional embeddings.
60
- """
61
- half = self.flow_t_size // 2
62
- freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, device=timesteps.device) / half).type(timesteps.type())
63
- args = timesteps[:, None] * freqs[None] * scale
64
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
65
- if self.flow_t_size % 2:
66
- embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
67
- return embedding
68
-
69
- def forward(self, timestep, resolution, aspect_ratio, batch_size, hidden_dtype):
70
- timesteps_proj = self.timestep_embedding(timestep)
71
- timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
72
-
73
- if self.use_additional_conditions:
74
- resolution_emb = self.additional_condition_proj(resolution.flatten()).to(hidden_dtype)
75
- resolution_emb = self.resolution_embedder(resolution_emb).reshape(batch_size, -1)
76
- aspect_ratio_emb = self.additional_condition_proj(aspect_ratio.flatten()).to(hidden_dtype)
77
- aspect_ratio_emb = self.aspect_ratio_embedder(aspect_ratio_emb).reshape(batch_size, -1)
78
- conditioning = timesteps_emb + torch.cat([resolution_emb, aspect_ratio_emb], dim=1)
79
- else:
80
- conditioning = timesteps_emb
81
-
82
- return conditioning
83
-
84
- class AdaLayerNormSingleFlow(nn.Module):
85
- r"""
86
- Norm layer adaptive layer norm single (adaLN-single).
87
-
88
- As proposed in PixArt-Alpha (see: https://arxiv.org/abs/2310.00426; Section 2.3).
89
-
90
- Parameters:
91
- embedding_dim (`int`): The size of each embedding vector.
92
- use_additional_conditions (`bool`): To use additional conditions for normalization or not.
93
- """
94
-
95
- def __init__(self, embedding_dim: int, use_additional_conditions: bool = False):
96
- super().__init__()
97
-
98
- self.emb = PixArtAlphaCombinedFlowEmbeddings(
99
- embedding_dim, size_emb_dim=embedding_dim // 3, use_additional_conditions=use_additional_conditions
100
- )
101
-
102
- self.silu = nn.SiLU()
103
- self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
104
-
105
- def forward(
106
- self,
107
- timestep: torch.Tensor,
108
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
109
- batch_size: Optional[int] = None,
110
- hidden_dtype: Optional[torch.dtype] = None,
111
- ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
112
- # No modulation happening here.
113
- embedded_timestep = self.emb(timestep, **added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_dtype)
114
- return self.linear(self.silu(embedded_timestep)), embedded_timestep
115
-
116
-
117
- @dataclass
118
- class Transformer2DModelOutput(BaseOutput):
119
- """
120
- The output of [`Transformer2DModel`].
121
-
122
- Args:
123
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
124
- The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
125
- distributions for the unnoised latent pixels.
126
- """
127
-
128
- sample: torch.FloatTensor
129
-
130
-
131
- class Transformer2DModel(ModelMixin, ConfigMixin):
132
- """
133
- A 2D Transformer model for image-like data.
134
-
135
- Parameters:
136
- num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
137
- attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
138
- in_channels (`int`, *optional*):
139
- The number of channels in the input and output (specify if the input is **continuous**).
140
- num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
141
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
142
- cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
143
- sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
144
- This is fixed during training since it is used to learn a number of position embeddings.
145
- num_vector_embeds (`int`, *optional*):
146
- The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
147
- Includes the class for the masked latent pixel.
148
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
149
- num_embeds_ada_norm ( `int`, *optional*):
150
- The number of diffusion steps used during training. Pass if at least one of the norm_layers is
151
- `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
152
- added to the hidden states.
153
-
154
- During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
155
- attention_bias (`bool`, *optional*):
156
- Configure if the `TransformerBlocks` attention should contain a bias parameter.
157
- """
158
-
159
- _supports_gradient_checkpointing = True
160
-
161
- @register_to_config
162
- def __init__(
163
- self,
164
- num_attention_heads: int = 16,
165
- attention_head_dim: int = 88,
166
- in_channels: Optional[int] = None,
167
- out_channels: Optional[int] = None,
168
- num_layers: int = 1,
169
- dropout: float = 0.0,
170
- norm_num_groups: int = 32,
171
- cross_attention_dim: Optional[int] = None,
172
- attention_bias: bool = False,
173
- sample_size: Optional[int] = None,
174
- num_vector_embeds: Optional[int] = None,
175
- patch_size: Optional[int] = None,
176
- activation_fn: str = "geglu",
177
- num_embeds_ada_norm: Optional[int] = None,
178
- use_linear_projection: bool = False,
179
- only_cross_attention: bool = False,
180
- double_self_attention: bool = False,
181
- upcast_attention: bool = False,
182
- norm_type: str = "layer_norm",
183
- norm_elementwise_affine: bool = True,
184
- norm_eps: float = 1e-5,
185
- attention_type: str = "default",
186
- caption_channels: int = None,
187
- ):
188
- super().__init__()
189
- self.use_linear_projection = use_linear_projection
190
- self.num_attention_heads = num_attention_heads
191
- self.attention_head_dim = attention_head_dim
192
- inner_dim = num_attention_heads * attention_head_dim
193
-
194
- conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
195
- linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
196
-
197
- # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
198
- # Define whether input is continuous or discrete depending on configuration
199
- self.is_input_continuous = (in_channels is not None) and (patch_size is None)
200
- self.is_input_vectorized = num_vector_embeds is not None
201
- self.is_input_patches = in_channels is not None and patch_size is not None
202
-
203
- if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
204
- deprecation_message = (
205
- f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
206
- " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."
207
- " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
208
- " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
209
- " would be very nice if you could open a Pull request for the `transformer/config.json` file"
210
- )
211
- deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
212
- norm_type = "ada_norm"
213
-
214
- if self.is_input_continuous and self.is_input_vectorized:
215
- raise ValueError(
216
- f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
217
- " sure that either `in_channels` or `num_vector_embeds` is None."
218
- )
219
- elif self.is_input_vectorized and self.is_input_patches:
220
- raise ValueError(
221
- f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
222
- " sure that either `num_vector_embeds` or `num_patches` is None."
223
- )
224
- elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
225
- raise ValueError(
226
- f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
227
- f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
228
- )
229
-
230
- # 2. Define input layers
231
- if self.is_input_continuous:
232
- self.in_channels = in_channels
233
-
234
- self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
235
- if use_linear_projection:
236
- self.proj_in = linear_cls(in_channels, inner_dim)
237
- else:
238
- self.proj_in = conv_cls(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
239
- elif self.is_input_vectorized:
240
- assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
241
- assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"
242
-
243
- self.height = sample_size
244
- self.width = sample_size
245
- self.num_vector_embeds = num_vector_embeds
246
- self.num_latent_pixels = self.height * self.width
247
-
248
- self.latent_image_embedding = ImagePositionalEmbeddings(
249
- num_embed=num_vector_embeds, embed_dim=inner_dim, height=self.height, width=self.width
250
- )
251
- elif self.is_input_patches:
252
- assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"
253
-
254
- self.height = sample_size
255
- self.width = sample_size
256
-
257
- self.patch_size = patch_size
258
- interpolation_scale = self.config.sample_size // 64 # => 64 (= 512 pixart) has interpolation scale 1
259
- interpolation_scale = max(interpolation_scale, 1)
260
- self.pos_embed = PatchEmbed(
261
- height=sample_size,
262
- width=sample_size,
263
- patch_size=patch_size,
264
- in_channels=in_channels,
265
- embed_dim=inner_dim,
266
- interpolation_scale=interpolation_scale,
267
- )
268
-
269
- # 3. Define transformers blocks
270
- self.transformer_blocks = nn.ModuleList(
271
- [
272
- BasicTransformerBlock(
273
- inner_dim,
274
- num_attention_heads,
275
- attention_head_dim,
276
- dropout=dropout,
277
- cross_attention_dim=cross_attention_dim,
278
- activation_fn=activation_fn,
279
- num_embeds_ada_norm=num_embeds_ada_norm,
280
- attention_bias=attention_bias,
281
- only_cross_attention=only_cross_attention,
282
- double_self_attention=double_self_attention,
283
- upcast_attention=upcast_attention,
284
- norm_type=norm_type,
285
- norm_elementwise_affine=norm_elementwise_affine,
286
- norm_eps=norm_eps,
287
- attention_type=attention_type,
288
- )
289
- for d in range(num_layers)
290
- ]
291
- )
292
-
293
- # 4. Define output layers
294
- self.out_channels = in_channels if out_channels is None else out_channels
295
- if self.is_input_continuous:
296
- # TODO: should use out_channels for continuous projections
297
- if use_linear_projection:
298
- self.proj_out = linear_cls(inner_dim, in_channels)
299
- else:
300
- self.proj_out = conv_cls(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
301
- elif self.is_input_vectorized:
302
- self.norm_out = nn.LayerNorm(inner_dim)
303
- self.out = nn.Linear(inner_dim, self.num_vector_embeds - 1)
304
- elif self.is_input_patches and norm_type != "ada_norm_single":
305
- self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
306
- self.proj_out_1 = nn.Linear(inner_dim, 2 * inner_dim)
307
- self.proj_out_2 = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
308
- elif self.is_input_patches and norm_type == "ada_norm_single":
309
- self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
310
- self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5)
311
- self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
312
-
313
- # 5. PixArt-Alpha blocks.
314
- self.adaln_single = None
315
- self.use_additional_conditions = False
316
- if norm_type == "ada_norm_single":
317
- self.use_additional_conditions = self.config.sample_size == 128
318
- # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
319
- # additional conditions until we find better name
320
- self.adaln_single = AdaLayerNormSingleFlow(inner_dim, use_additional_conditions=self.use_additional_conditions)
321
-
322
- self.caption_projection = None
323
- if caption_channels is not None:
324
- self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
325
-
326
- self.gradient_checkpointing = False
327
-
328
- def _set_gradient_checkpointing(self, module, value=False):
329
- if hasattr(module, "gradient_checkpointing"):
330
- module.gradient_checkpointing = value
331
-
332
- def forward(
333
- self,
334
- hidden_states: torch.Tensor,
335
- encoder_hidden_states: Optional[torch.Tensor] = None,
336
- timestep: Optional[torch.LongTensor] = None,
337
- added_cond_kwargs: Dict[str, torch.Tensor] = None,
338
- class_labels: Optional[torch.LongTensor] = None,
339
- cross_attention_kwargs: Dict[str, Any] = None,
340
- attention_mask: Optional[torch.Tensor] = None,
341
- encoder_attention_mask: Optional[torch.Tensor] = None,
342
- return_dict: bool = True,
343
- ):
344
- """
345
- The [`Transformer2DModel`] forward method.
346
-
347
- Args:
348
- hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
349
- Input `hidden_states`.
350
- encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
351
- Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
352
- self-attention.
353
- timestep ( `torch.LongTensor`, *optional*):
354
- Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
355
- class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
356
- Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
357
- `AdaLayerZeroNorm`.
358
- cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
359
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
360
- `self.processor` in
361
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
362
- attention_mask ( `torch.Tensor`, *optional*):
363
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
364
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
365
- negative values to the attention scores corresponding to "discard" tokens.
366
- encoder_attention_mask ( `torch.Tensor`, *optional*):
367
- Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
368
-
369
- * Mask `(batch, sequence_length)` True = keep, False = discard.
370
- * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
371
-
372
- If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
373
- above. This bias will be added to the cross-attention scores.
374
- return_dict (`bool`, *optional*, defaults to `True`):
375
- Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
376
- tuple.
377
-
378
- Returns:
379
- If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
380
- `tuple` where the first element is the sample tensor.
381
- """
382
- # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
383
- # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
384
- # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
385
- # expects mask of shape:
386
- # [batch, key_tokens]
387
- # adds singleton query_tokens dimension:
388
- # [batch, 1, key_tokens]
389
- # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
390
- # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
391
- # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
392
- if attention_mask is not None and attention_mask.ndim == 2:
393
- # assume that mask is expressed as:
394
- # (1 = keep, 0 = discard)
395
- # convert mask into a bias that can be added to attention scores:
396
- # (keep = +0, discard = -10000.0)
397
- attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
398
- attention_mask = attention_mask.unsqueeze(1)
399
-
400
- # convert encoder_attention_mask to a bias the same way we do for attention_mask
401
- if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
402
- encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
403
- encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
404
-
405
- # Retrieve lora scale.
406
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
407
-
408
- # 1. Input
409
- if self.is_input_continuous:
410
- batch, _, height, width = hidden_states.shape
411
- residual = hidden_states
412
-
413
- hidden_states = self.norm(hidden_states)
414
- if not self.use_linear_projection:
415
- hidden_states = (
416
- self.proj_in(hidden_states, scale=lora_scale)
417
- if not USE_PEFT_BACKEND
418
- else self.proj_in(hidden_states)
419
- )
420
- inner_dim = hidden_states.shape[1]
421
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
422
- else:
423
- inner_dim = hidden_states.shape[1]
424
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
425
- hidden_states = (
426
- self.proj_in(hidden_states, scale=lora_scale)
427
- if not USE_PEFT_BACKEND
428
- else self.proj_in(hidden_states)
429
- )
430
-
431
- elif self.is_input_vectorized:
432
- hidden_states = self.latent_image_embedding(hidden_states)
433
- elif self.is_input_patches:
434
- height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
435
- hidden_states = self.pos_embed(hidden_states)
436
-
437
- if self.adaln_single is not None:
438
- if self.use_additional_conditions and added_cond_kwargs is None:
439
- raise ValueError(
440
- "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
441
- )
442
- batch_size = hidden_states.shape[0]
443
- timestep, embedded_timestep = self.adaln_single(
444
- timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
445
- )
446
-
447
- # 2. Blocks
448
- if self.caption_projection is not None:
449
- batch_size = hidden_states.shape[0]
450
- encoder_hidden_states = self.caption_projection(encoder_hidden_states)
451
- encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
452
-
453
- for block in self.transformer_blocks:
454
- if self.training and self.gradient_checkpointing:
455
-
456
- def create_custom_forward(module, return_dict=None):
457
- def custom_forward(*inputs):
458
- if return_dict is not None:
459
- return module(*inputs, return_dict=return_dict)
460
- else:
461
- return module(*inputs)
462
-
463
- return custom_forward
464
-
465
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
466
- hidden_states = torch.utils.checkpoint.checkpoint(
467
- create_custom_forward(block),
468
- hidden_states,
469
- attention_mask,
470
- encoder_hidden_states,
471
- encoder_attention_mask,
472
- timestep,
473
- cross_attention_kwargs,
474
- class_labels,
475
- **ckpt_kwargs,
476
- )
477
- else:
478
- hidden_states = block(
479
- hidden_states,
480
- attention_mask=attention_mask,
481
- encoder_hidden_states=encoder_hidden_states,
482
- encoder_attention_mask=encoder_attention_mask,
483
- timestep=timestep,
484
- cross_attention_kwargs=cross_attention_kwargs,
485
- class_labels=class_labels,
486
- )
487
-
488
- # 3. Output
489
- if self.is_input_continuous:
490
- if not self.use_linear_projection:
491
- hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
492
- hidden_states = (
493
- self.proj_out(hidden_states, scale=lora_scale)
494
- if not USE_PEFT_BACKEND
495
- else self.proj_out(hidden_states)
496
- )
497
- else:
498
- hidden_states = (
499
- self.proj_out(hidden_states, scale=lora_scale)
500
- if not USE_PEFT_BACKEND
501
- else self.proj_out(hidden_states)
502
- )
503
- hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
504
-
505
- output = hidden_states + residual
506
- elif self.is_input_vectorized:
507
- hidden_states = self.norm_out(hidden_states)
508
- logits = self.out(hidden_states)
509
- # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
510
- logits = logits.permute(0, 2, 1)
511
-
512
- # log(p(x_0))
513
- output = F.log_softmax(logits.double(), dim=1).float()
514
-
515
- if self.is_input_patches:
516
- if self.config.norm_type != "ada_norm_single":
517
- conditioning = self.transformer_blocks[0].norm1.emb(
518
- timestep, class_labels, hidden_dtype=hidden_states.dtype
519
- )
520
- shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
521
- hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
522
- hidden_states = self.proj_out_2(hidden_states)
523
- elif self.config.norm_type == "ada_norm_single":
524
- shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
525
- hidden_states = self.norm_out(hidden_states)
526
- # Modulation
527
- hidden_states = hidden_states * (1 + scale) + shift
528
- hidden_states = self.proj_out(hidden_states)
529
- hidden_states = hidden_states.squeeze(1)
530
-
531
- # unpatchify
532
- if self.adaln_single is None:
533
- height = width = int(hidden_states.shape[1] ** 0.5)
534
- hidden_states = hidden_states.reshape(
535
- shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
536
- )
537
- hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
538
- output = hidden_states.reshape(
539
- shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
540
- )
541
-
542
- if not return_dict:
543
- return (output,)
544
-
545
- return Transformer2DModelOutput(sample=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models/transformer_2d_rot_emb.py DELETED
@@ -1,487 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from dataclasses import dataclass
15
- from typing import Any, Dict, Optional
16
-
17
- import torch
18
- import torch.nn.functional as F
19
- from torch import nn
20
-
21
- from diffusers.configuration_utils import ConfigMixin, register_to_config
22
- from diffusers.models.embeddings import ImagePositionalEmbeddings
23
- from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, is_torch_version
24
- from models.attention_add_rot_emb import BasicTransformerBlock
25
- from diffusers.models.embeddings import PatchEmbed, PixArtAlphaTextProjection
26
- from diffusers.models.lora import LoRACompatibleConv, LoRACompatibleLinear
27
- from diffusers.models.modeling_utils import ModelMixin
28
- from diffusers.models.normalization import AdaLayerNormSingle
29
-
30
-
31
- @dataclass
32
- class Transformer2DModelOutput(BaseOutput):
33
- """
34
- The output of [`Transformer2DModel`].
35
-
36
- Args:
37
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
38
- The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
39
- distributions for the unnoised latent pixels.
40
- """
41
-
42
- sample: torch.FloatTensor
43
-
44
-
45
- class Transformer2DModel(ModelMixin, ConfigMixin):
46
- """
47
- A 2D Transformer model for image-like data.
48
-
49
- Parameters:
50
- num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
51
- attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
52
- in_channels (`int`, *optional*):
53
- The number of channels in the input and output (specify if the input is **continuous**).
54
- num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
55
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
56
- cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
57
- sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
58
- This is fixed during training since it is used to learn a number of position embeddings.
59
- num_vector_embeds (`int`, *optional*):
60
- The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
61
- Includes the class for the masked latent pixel.
62
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
63
- num_embeds_ada_norm ( `int`, *optional*):
64
- The number of diffusion steps used during training. Pass if at least one of the norm_layers is
65
- `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
66
- added to the hidden states.
67
-
68
- During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
69
- attention_bias (`bool`, *optional*):
70
- Configure if the `TransformerBlocks` attention should contain a bias parameter.
71
- """
72
-
73
- _supports_gradient_checkpointing = True
74
-
75
- @register_to_config
76
- def __init__(
77
- self,
78
- num_attention_heads: int = 16,
79
- attention_head_dim: int = 88,
80
- in_channels: Optional[int] = None,
81
- out_channels: Optional[int] = None,
82
- num_layers: int = 1,
83
- dropout: float = 0.0,
84
- norm_num_groups: int = 32,
85
- cross_attention_dim: Optional[int] = None,
86
- attention_bias: bool = False,
87
- sample_size: Optional[int] = None,
88
- num_vector_embeds: Optional[int] = None,
89
- patch_size: Optional[int] = None,
90
- activation_fn: str = "geglu",
91
- num_embeds_ada_norm: Optional[int] = None,
92
- use_linear_projection: bool = False,
93
- only_cross_attention: bool = False,
94
- double_self_attention: bool = False,
95
- upcast_attention: bool = False,
96
- norm_type: str = "layer_norm",
97
- norm_elementwise_affine: bool = True,
98
- norm_eps: float = 1e-5,
99
- attention_type: str = "default",
100
- caption_channels: int = None,
101
- ):
102
- super().__init__()
103
- self.use_linear_projection = use_linear_projection
104
- self.num_attention_heads = num_attention_heads
105
- self.attention_head_dim = attention_head_dim
106
- inner_dim = num_attention_heads * attention_head_dim
107
-
108
- conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
109
- linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
110
-
111
- # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
112
- # Define whether input is continuous or discrete depending on configuration
113
- self.is_input_continuous = (in_channels is not None) and (patch_size is None)
114
- self.is_input_vectorized = num_vector_embeds is not None
115
- self.is_input_patches = in_channels is not None and patch_size is not None
116
-
117
- if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
118
- deprecation_message = (
119
- f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
120
- " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."
121
- " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
122
- " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
123
- " would be very nice if you could open a Pull request for the `transformer/config.json` file"
124
- )
125
- deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
126
- norm_type = "ada_norm"
127
-
128
- if self.is_input_continuous and self.is_input_vectorized:
129
- raise ValueError(
130
- f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
131
- " sure that either `in_channels` or `num_vector_embeds` is None."
132
- )
133
- elif self.is_input_vectorized and self.is_input_patches:
134
- raise ValueError(
135
- f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
136
- " sure that either `num_vector_embeds` or `num_patches` is None."
137
- )
138
- elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
139
- raise ValueError(
140
- f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
141
- f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
142
- )
143
-
144
- # 2. Define input layers
145
- if self.is_input_continuous:
146
- self.in_channels = in_channels
147
-
148
- self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
149
- if use_linear_projection:
150
- self.proj_in = linear_cls(in_channels, inner_dim)
151
- else:
152
- self.proj_in = conv_cls(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
153
- elif self.is_input_vectorized:
154
- assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
155
- assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"
156
-
157
- self.height = sample_size
158
- self.width = sample_size
159
- self.num_vector_embeds = num_vector_embeds
160
- self.num_latent_pixels = self.height * self.width
161
-
162
- self.latent_image_embedding = ImagePositionalEmbeddings(
163
- num_embed=num_vector_embeds, embed_dim=inner_dim, height=self.height, width=self.width
164
- )
165
- elif self.is_input_patches:
166
- assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"
167
-
168
- self.height = sample_size
169
- self.width = sample_size
170
-
171
- self.patch_size = patch_size
172
- interpolation_scale = self.config.sample_size // 64 # => 64 (= 512 pixart) has interpolation scale 1
173
- interpolation_scale = max(interpolation_scale, 1)
174
- self.pos_embed = PatchEmbed(
175
- height=sample_size,
176
- width=sample_size,
177
- patch_size=patch_size,
178
- in_channels=in_channels,
179
- embed_dim=inner_dim,
180
- interpolation_scale=interpolation_scale,
181
- )
182
-
183
- # 3. Define transformers blocks
184
- self.transformer_blocks = nn.ModuleList(
185
- [
186
- BasicTransformerBlock(
187
- inner_dim,
188
- num_attention_heads,
189
- attention_head_dim,
190
- dropout=dropout,
191
- cross_attention_dim=cross_attention_dim,
192
- activation_fn=activation_fn,
193
- num_embeds_ada_norm=num_embeds_ada_norm,
194
- attention_bias=attention_bias,
195
- only_cross_attention=only_cross_attention,
196
- double_self_attention=double_self_attention,
197
- upcast_attention=upcast_attention,
198
- norm_type=norm_type,
199
- norm_elementwise_affine=norm_elementwise_affine,
200
- norm_eps=norm_eps,
201
- attention_type=attention_type,
202
- )
203
- for d in range(num_layers)
204
- ]
205
- )
206
-
207
- # 4. Define output layers
208
- self.out_channels = in_channels if out_channels is None else out_channels
209
- if self.is_input_continuous:
210
- # TODO: should use out_channels for continuous projections
211
- if use_linear_projection:
212
- self.proj_out = linear_cls(inner_dim, in_channels)
213
- else:
214
- self.proj_out = conv_cls(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
215
- elif self.is_input_vectorized:
216
- self.norm_out = nn.LayerNorm(inner_dim)
217
- self.out = nn.Linear(inner_dim, self.num_vector_embeds - 1)
218
- elif self.is_input_patches and norm_type != "ada_norm_single":
219
- self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
220
- self.proj_out_1 = nn.Linear(inner_dim, 2 * inner_dim)
221
- self.proj_out_2 = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
222
- elif self.is_input_patches and norm_type == "ada_norm_single":
223
- self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
224
- self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5)
225
- self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
226
-
227
- # 5. PixArt-Alpha blocks.
228
- self.adaln_single = None
229
- self.use_additional_conditions = False
230
- if norm_type == "ada_norm_single":
231
- self.use_additional_conditions = self.config.sample_size == 128
232
- # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
233
- # additional conditions until we find better name
234
- self.adaln_single = AdaLayerNormSingle(inner_dim, use_additional_conditions=self.use_additional_conditions)
235
-
236
- self.caption_projection = None
237
- if caption_channels is not None:
238
- self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
239
-
240
- self.gradient_checkpointing = False
241
-
242
- def _set_gradient_checkpointing(self, module, value=False):
243
- if hasattr(module, "gradient_checkpointing"):
244
- module.gradient_checkpointing = value
245
-
246
- def forward(
247
- self,
248
- hidden_states: torch.Tensor,
249
- encoder_hidden_states: Optional[torch.Tensor] = None,
250
- timestep: Optional[torch.LongTensor] = None,
251
- added_cond_kwargs: Dict[str, torch.Tensor] = None,
252
- class_labels: Optional[torch.LongTensor] = None,
253
- cross_attention_kwargs: Dict[str, Any] = None,
254
- attention_mask: Optional[torch.Tensor] = None,
255
- encoder_attention_mask: Optional[torch.Tensor] = None,
256
- return_dict: bool = True,
257
- ):
258
- """
259
- The [`Transformer2DModel`] forward method.
260
-
261
- Args:
262
- hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
263
- Input `hidden_states`.
264
- encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
265
- Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
266
- self-attention.
267
- timestep ( `torch.LongTensor`, *optional*):
268
- Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
269
- class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
270
- Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
271
- `AdaLayerZeroNorm`.
272
- cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
273
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
274
- `self.processor` in
275
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
276
- attention_mask ( `torch.Tensor`, *optional*):
277
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
278
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
279
- negative values to the attention scores corresponding to "discard" tokens.
280
- encoder_attention_mask ( `torch.Tensor`, *optional*):
281
- Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
282
-
283
- * Mask `(batch, sequence_length)` True = keep, False = discard.
284
- * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
285
-
286
- If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
287
- above. This bias will be added to the cross-attention scores.
288
- return_dict (`bool`, *optional*, defaults to `True`):
289
- Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
290
- tuple.
291
-
292
- Returns:
293
- If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
294
- `tuple` where the first element is the sample tensor.
295
- """
296
- # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
297
- # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
298
- # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
299
- # expects mask of shape:
300
- # [batch, key_tokens]
301
- # adds singleton query_tokens dimension:
302
- # [batch, 1, key_tokens]
303
- # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
304
- # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
305
- # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
306
- if attention_mask is not None and attention_mask.ndim == 2:
307
- # assume that mask is expressed as:
308
- # (1 = keep, 0 = discard)
309
- # convert mask into a bias that can be added to attention scores:
310
- # (keep = +0, discard = -10000.0)
311
- attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
312
- attention_mask = attention_mask.unsqueeze(1)
313
-
314
- # convert encoder_attention_mask to a bias the same way we do for attention_mask
315
- if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
316
- encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
317
- encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
318
-
319
- # Retrieve lora scale.
320
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
321
-
322
- # 1. Input
323
- print("before input hidden_states.shape", hidden_states.shape)
324
- # print("is_input_patches", self.is_input_patches)
325
- #true
326
- # print("is_input_vectorized", self.is_input_vectorized)
327
- # print("is_input_continuous", self.is_input_continuous)
328
- #false
329
- # print("use_linear_projection", self.use_linear_projection)
330
- #false
331
- if self.is_input_continuous:
332
- batch, _, height, width = hidden_states.shape
333
- residual = hidden_states
334
-
335
- hidden_states = self.norm(hidden_states)
336
- if not self.use_linear_projection:
337
- hidden_states = (
338
- self.proj_in(hidden_states, scale=lora_scale)
339
- if not USE_PEFT_BACKEND
340
- else self.proj_in(hidden_states)
341
- )
342
- # print("input 1 hidden_states.shape", hidden_states.shape)
343
- inner_dim = hidden_states.shape[1]
344
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
345
- # print("input 2 hidden_states.shape", hidden_states.shape)
346
- else:
347
- inner_dim = hidden_states.shape[1]
348
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
349
- hidden_states = (
350
- self.proj_in(hidden_states, scale=lora_scale)
351
- if not USE_PEFT_BACKEND
352
- else self.proj_in(hidden_states)
353
- )
354
-
355
- elif self.is_input_vectorized:
356
- hidden_states = self.latent_image_embedding(hidden_states)
357
- elif self.is_input_patches:
358
- height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
359
- # print("before patches hidden_states.shape", hidden_states.shape)
360
- hidden_states = self.pos_embed(hidden_states)
361
- # print("after patches hidden_states.shape", hidden_states.shape)
362
-
363
- if self.adaln_single is not None:
364
- if self.use_additional_conditions and added_cond_kwargs is None:
365
- raise ValueError(
366
- "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
367
- )
368
- batch_size = hidden_states.shape[0]
369
- print("time step before adaln_single", timestep)
370
- timestep, embedded_timestep = self.adaln_single(
371
- timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
372
- )
373
- print("time step after adaln_single", timestep.shape)
374
- print("embedded_timestep after adaln_single", embedded_timestep.shape)
375
-
376
-
377
- # 2. Blocks
378
- print("before blocks hidden_states.shape", hidden_states.shape)
379
- if self.caption_projection is not None:
380
- batch_size = hidden_states.shape[0]
381
- encoder_hidden_states = self.caption_projection(encoder_hidden_states)
382
- encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
383
-
384
- for block in self.transformer_blocks:
385
- if self.training and self.gradient_checkpointing:
386
-
387
- def create_custom_forward(module, return_dict=None):
388
- def custom_forward(*inputs):
389
- if return_dict is not None:
390
- return module(*inputs, return_dict=return_dict)
391
- else:
392
- return module(*inputs)
393
-
394
- return custom_forward
395
-
396
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
397
- hidden_states = torch.utils.checkpoint.checkpoint(
398
- create_custom_forward(block),
399
- hidden_states,
400
- attention_mask,
401
- encoder_hidden_states,
402
- encoder_attention_mask,
403
- timestep,
404
- cross_attention_kwargs,
405
- class_labels,
406
- **ckpt_kwargs,
407
- )
408
- else:
409
- hidden_states = block(
410
- hidden_states,
411
- attention_mask=attention_mask,
412
- encoder_hidden_states=encoder_hidden_states,
413
- encoder_attention_mask=encoder_attention_mask,
414
- timestep=timestep,
415
- cross_attention_kwargs=cross_attention_kwargs,
416
- class_labels=class_labels,
417
- )
418
-
419
-
420
- # 3. Output
421
- print("after blocks hidden_states.shape", hidden_states.shape)
422
- if self.is_input_continuous:
423
- print("1")
424
- if not self.use_linear_projection:
425
- print("1 hidden_states.shape", hidden_states.shape)
426
- hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
427
- hidden_states = (
428
- self.proj_out(hidden_states, scale=lora_scale)
429
- if not USE_PEFT_BACKEND
430
- else self.proj_out(hidden_states)
431
- )
432
- print("2 hidden_states.shape", hidden_states.shape)
433
- else:
434
- hidden_states = (
435
- self.proj_out(hidden_states, scale=lora_scale)
436
- if not USE_PEFT_BACKEND
437
- else self.proj_out(hidden_states)
438
- )
439
- hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
440
-
441
- output = hidden_states + residual
442
- elif self.is_input_vectorized:
443
- print("2")
444
- hidden_states = self.norm_out(hidden_states)
445
- logits = self.out(hidden_states)
446
- # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
447
- logits = logits.permute(0, 2, 1)
448
-
449
- # log(p(x_0))
450
- output = F.log_softmax(logits.double(), dim=1).float()
451
-
452
- if self.is_input_patches:
453
- print("3")
454
- if self.config.norm_type != "ada_norm_single":
455
- conditioning = self.transformer_blocks[0].norm1.emb(
456
- timestep, class_labels, hidden_dtype=hidden_states.dtype
457
- )
458
- shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
459
- hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
460
- hidden_states = self.proj_out_2(hidden_states)
461
- elif self.config.norm_type == "ada_norm_single":
462
- shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
463
- hidden_states = self.norm_out(hidden_states)
464
- # Modulation
465
- hidden_states = hidden_states * (1 + scale) + shift
466
- print("before proj_out hidden_states.shape", hidden_states.shape)
467
- hidden_states = self.proj_out(hidden_states)
468
- print("after proj_out hidden_states.shape", hidden_states.shape)
469
-
470
- hidden_states = hidden_states.squeeze(1)
471
-
472
- # unpatchify
473
- if self.adaln_single is None:
474
- print("4")
475
- height = width = int(hidden_states.shape[1] ** 0.5)
476
- hidden_states = hidden_states.reshape(
477
- shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
478
- )
479
- hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
480
- output = hidden_states.reshape(
481
- shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
482
- )
483
-
484
- if not return_dict:
485
- return (output,)
486
-
487
- return Transformer2DModelOutput(sample=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models/unet_2d_condition_additionalemb.py DELETED
@@ -1,996 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from dataclasses import dataclass
15
- from typing import Any, Dict, List, Optional, Tuple, Union
16
-
17
- import torch
18
- import torch.nn as nn
19
- import torch.utils.checkpoint
20
-
21
- from diffusers.configuration_utils import ConfigMixin, register_to_config
22
- from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
23
- from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
24
- from diffusers.models.activations import get_activation
25
- from diffusers.models.embeddings import (
26
- GaussianFourierProjection,
27
- GLIGENTextBoundingboxProjection,
28
- ImageHintTimeEmbedding,
29
- ImageProjection,
30
- ImageTimeEmbedding,
31
- TextImageProjection,
32
- TextImageTimeEmbedding,
33
- TextTimeEmbedding,
34
- TimestepEmbedding,
35
- Timesteps,
36
- )
37
- from diffusers.models.modeling_utils import ModelMixin
38
- from diffusers.models.unet_2d_blocks import (
39
- UNetMidBlock2D,
40
- UNetMidBlock2DCrossAttn,
41
- UNetMidBlock2DSimpleCrossAttn,
42
- get_down_block,
43
- get_up_block,
44
- )
45
-
46
-
47
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
48
-
49
-
50
- @dataclass
51
- class UNet2DConditionOutput(BaseOutput):
52
- """
53
- The output of [`UNet2DConditionModel`].
54
-
55
- Args:
56
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
57
- The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
58
- """
59
-
60
- sample: torch.FloatTensor = None
61
-
62
-
63
- class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin):
64
- r"""
65
- A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
66
- shaped output.
67
-
68
- This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
69
- for all models (such as downloading or saving).
70
-
71
- Parameters:
72
- sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
73
- Height and width of input/output sample.
74
- in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
75
- out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
76
- center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
77
- flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
78
- Whether to flip the sin to cos in the time embedding.
79
- freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
80
- down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
81
- The tuple of downsample blocks to use.
82
- mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
83
- Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
84
- `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
85
- up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
86
- The tuple of upsample blocks to use.
87
- only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
88
- Whether to include self-attention in the basic transformer blocks, see
89
- [`~models.attention.BasicTransformerBlock`].
90
- block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
91
- The tuple of output channels for each block.
92
- layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
93
- downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
94
- mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
95
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
96
- act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
97
- norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
98
- If `None`, normalization and activation layers is skipped in post-processing.
99
- norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
100
- cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
101
- The dimension of the cross attention features.
102
- transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
103
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
104
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
105
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
106
- reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
107
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
108
- blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
109
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
110
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
111
- encoder_hid_dim (`int`, *optional*, defaults to None):
112
- If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
113
- dimension to `cross_attention_dim`.
114
- encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
115
- If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
116
- embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
117
- attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
118
- num_attention_heads (`int`, *optional*):
119
- The number of attention heads. If not defined, defaults to `attention_head_dim`
120
- resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
121
- for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
122
- class_embed_type (`str`, *optional*, defaults to `None`):
123
- The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
124
- `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
125
- addition_embed_type (`str`, *optional*, defaults to `None`):
126
- Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
127
- "text". "text" will use the `TextTimeEmbedding` layer.
128
- addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
129
- Dimension for the timestep embeddings.
130
- num_class_embeds (`int`, *optional*, defaults to `None`):
131
- Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
132
- class conditioning with `class_embed_type` equal to `None`.
133
- time_embedding_type (`str`, *optional*, defaults to `positional`):
134
- The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
135
- time_embedding_dim (`int`, *optional*, defaults to `None`):
136
- An optional override for the dimension of the projected time embedding.
137
- time_embedding_act_fn (`str`, *optional*, defaults to `None`):
138
- Optional activation function to use only once on the time embeddings before they are passed to the rest of
139
- the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
140
- timestep_post_act (`str`, *optional*, defaults to `None`):
141
- The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
142
- time_cond_proj_dim (`int`, *optional*, defaults to `None`):
143
- The dimension of `cond_proj` layer in the timestep embedding.
144
- conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`,
145
- *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`,
146
- *optional*): The dimension of the `class_labels` input when
147
- `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
148
- class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
149
- embeddings with the class embeddings.
150
- mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
151
- Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
152
- `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
153
- `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
154
- otherwise.
155
- """
156
-
157
- _supports_gradient_checkpointing = True
158
-
159
- @register_to_config
160
- def __init__(
161
- self,
162
- sample_size: Optional[int] = None,
163
- in_channels: int = 4,
164
- out_channels: int = 4,
165
- center_input_sample: bool = False,
166
- flip_sin_to_cos: bool = True,
167
- freq_shift: int = 0,
168
- down_block_types: Tuple[str] = (
169
- "CrossAttnDownBlock2D",
170
- "CrossAttnDownBlock2D",
171
- "CrossAttnDownBlock2D",
172
- "DownBlock2D",
173
- ),
174
- mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
175
- up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
176
- only_cross_attention: Union[bool, Tuple[bool]] = False,
177
- block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
178
- layers_per_block: Union[int, Tuple[int]] = 2,
179
- downsample_padding: int = 1,
180
- mid_block_scale_factor: float = 1,
181
- dropout: float = 0.0,
182
- act_fn: str = "silu",
183
- norm_num_groups: Optional[int] = 32,
184
- norm_eps: float = 1e-5,
185
- cross_attention_dim: Union[int, Tuple[int]] = 1280,
186
- transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
187
- reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
188
- encoder_hid_dim: Optional[int] = None,
189
- encoder_hid_dim_type: Optional[str] = None,
190
- attention_head_dim: Union[int, Tuple[int]] = 8,
191
- num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
192
- dual_cross_attention: bool = False,
193
- use_linear_projection: bool = False,
194
- class_embed_type: Optional[str] = None,
195
- addition_embed_type: Optional[str] = None,
196
- addition_time_embed_dim: Optional[int] = None,
197
- num_class_embeds: Optional[int] = None,
198
- upcast_attention: bool = False,
199
- resnet_time_scale_shift: str = "default",
200
- resnet_skip_time_act: bool = False,
201
- resnet_out_scale_factor: int = 1.0,
202
- time_embedding_type: str = "positional",
203
- time_embedding_dim: Optional[int] = None,
204
- time_embedding_act_fn: Optional[str] = None,
205
- timestep_post_act: Optional[str] = None,
206
- time_cond_proj_dim: Optional[int] = None,
207
- conv_in_kernel: int = 3,
208
- conv_out_kernel: int = 3,
209
- projection_class_embeddings_input_dim: Optional[int] = None,
210
- attention_type: str = "default",
211
- class_embeddings_concat: bool = False,
212
- mid_block_only_cross_attention: Optional[bool] = None,
213
- cross_attention_norm: Optional[str] = None,
214
- addition_embed_type_num_heads=64,
215
- ):
216
- super().__init__()
217
-
218
- self.sample_size = sample_size
219
-
220
- if num_attention_heads is not None:
221
- raise ValueError(
222
- "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19."
223
- )
224
-
225
- # If `num_attention_heads` is not defined (which is the case for most models)
226
- # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
227
- # The reason for this behavior is to correct for incorrectly named variables that were introduced
228
- # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
229
- # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
230
- # which is why we correct for the naming here.
231
- num_attention_heads = num_attention_heads or attention_head_dim
232
-
233
- # Check inputs
234
- if len(down_block_types) != len(up_block_types):
235
- raise ValueError(
236
- f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
237
- )
238
-
239
- if len(block_out_channels) != len(down_block_types):
240
- raise ValueError(
241
- f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
242
- )
243
-
244
- if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
245
- raise ValueError(
246
- f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
247
- )
248
-
249
- if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
250
- raise ValueError(
251
- f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
252
- )
253
-
254
- if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
255
- raise ValueError(
256
- f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
257
- )
258
-
259
- if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
260
- raise ValueError(
261
- f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
262
- )
263
-
264
- if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
265
- raise ValueError(
266
- f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
267
- )
268
- if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
269
- for layer_number_per_block in transformer_layers_per_block:
270
- if isinstance(layer_number_per_block, list):
271
- raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
272
-
273
- # input
274
- conv_in_padding = (conv_in_kernel - 1) // 2
275
- self.conv_in = nn.Conv2d(
276
- in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
277
- )
278
-
279
- # time
280
- if time_embedding_type == "fourier":
281
- time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
282
- if time_embed_dim % 2 != 0:
283
- raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
284
- self.time_proj = GaussianFourierProjection(
285
- time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
286
- )
287
- timestep_input_dim = time_embed_dim
288
- elif time_embedding_type == "positional":
289
- time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
290
-
291
- self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
292
- timestep_input_dim = block_out_channels[0]
293
- else:
294
- raise ValueError(
295
- f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
296
- )
297
-
298
- self.time_embedding = TimestepEmbedding(
299
- timestep_input_dim,
300
- time_embed_dim,
301
- act_fn=act_fn,
302
- post_act_fn=timestep_post_act,
303
- cond_proj_dim=time_cond_proj_dim,
304
- )
305
-
306
- if encoder_hid_dim_type is None and encoder_hid_dim is not None:
307
- encoder_hid_dim_type = "text_proj"
308
- self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
309
- logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
310
-
311
- if encoder_hid_dim is None and encoder_hid_dim_type is not None:
312
- raise ValueError(
313
- f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
314
- )
315
-
316
- if encoder_hid_dim_type == "text_proj":
317
- self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
318
- elif encoder_hid_dim_type == "text_image_proj":
319
- # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
320
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
321
- # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
322
- self.encoder_hid_proj = TextImageProjection(
323
- text_embed_dim=encoder_hid_dim,
324
- image_embed_dim=cross_attention_dim,
325
- cross_attention_dim=cross_attention_dim,
326
- )
327
- elif encoder_hid_dim_type == "image_proj":
328
- # Kandinsky 2.2
329
- self.encoder_hid_proj = ImageProjection(
330
- image_embed_dim=encoder_hid_dim,
331
- cross_attention_dim=cross_attention_dim,
332
- )
333
- elif encoder_hid_dim_type is not None:
334
- raise ValueError(
335
- f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
336
- )
337
- else:
338
- self.encoder_hid_proj = None
339
-
340
- # class embedding
341
- if class_embed_type is None and num_class_embeds is not None:
342
- self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
343
- elif class_embed_type == "timestep":
344
- self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
345
- elif class_embed_type == "identity":
346
- self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
347
- elif class_embed_type == "projection":
348
- if projection_class_embeddings_input_dim is None:
349
- raise ValueError(
350
- "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
351
- )
352
- # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
353
- # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
354
- # 2. it projects from an arbitrary input dimension.
355
- #
356
- # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
357
- # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
358
- # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
359
- self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
360
- elif class_embed_type == "simple_projection":
361
- if projection_class_embeddings_input_dim is None:
362
- raise ValueError(
363
- "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
364
- )
365
- self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
366
- else:
367
- self.class_embedding = None
368
-
369
- if addition_embed_type == "text":
370
- if encoder_hid_dim is not None:
371
- text_time_embedding_from_dim = encoder_hid_dim
372
- else:
373
- text_time_embedding_from_dim = cross_attention_dim
374
-
375
- self.add_embedding = TextTimeEmbedding(
376
- text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
377
- )
378
- elif addition_embed_type == "text_image":
379
- # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
380
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
381
- # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
382
- self.add_embedding = TextImageTimeEmbedding(
383
- text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
384
- )
385
- elif addition_embed_type == "text_time":
386
- self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
387
- self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
388
- elif addition_embed_type == "image":
389
- # Kandinsky 2.2
390
- self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
391
- elif addition_embed_type == "image_hint":
392
- # Kandinsky 2.2 ControlNet
393
- self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
394
- elif addition_embed_type is not None:
395
- raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
396
-
397
- if time_embedding_act_fn is None:
398
- self.time_embed_act = None
399
- else:
400
- self.time_embed_act = get_activation(time_embedding_act_fn)
401
-
402
- self.down_blocks = nn.ModuleList([])
403
- self.up_blocks = nn.ModuleList([])
404
-
405
- if isinstance(only_cross_attention, bool):
406
- if mid_block_only_cross_attention is None:
407
- mid_block_only_cross_attention = only_cross_attention
408
-
409
- only_cross_attention = [only_cross_attention] * len(down_block_types)
410
-
411
- if mid_block_only_cross_attention is None:
412
- mid_block_only_cross_attention = False
413
-
414
- if isinstance(num_attention_heads, int):
415
- num_attention_heads = (num_attention_heads,) * len(down_block_types)
416
-
417
- if isinstance(attention_head_dim, int):
418
- attention_head_dim = (attention_head_dim,) * len(down_block_types)
419
-
420
- if isinstance(cross_attention_dim, int):
421
- cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
422
-
423
- if isinstance(layers_per_block, int):
424
- layers_per_block = [layers_per_block] * len(down_block_types)
425
-
426
- if isinstance(transformer_layers_per_block, int):
427
- transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
428
-
429
- if class_embeddings_concat:
430
- # The time embeddings are concatenated with the class embeddings. The dimension of the
431
- # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
432
- # regular time embeddings
433
- blocks_time_embed_dim = time_embed_dim * 2
434
- else:
435
- blocks_time_embed_dim = time_embed_dim
436
-
437
- # down
438
- output_channel = block_out_channels[0]
439
- for i, down_block_type in enumerate(down_block_types):
440
- input_channel = output_channel
441
- output_channel = block_out_channels[i]
442
- is_final_block = i == len(block_out_channels) - 1
443
-
444
- down_block = get_down_block(
445
- down_block_type,
446
- num_layers=layers_per_block[i],
447
- transformer_layers_per_block=transformer_layers_per_block[i],
448
- in_channels=input_channel,
449
- out_channels=output_channel,
450
- temb_channels=blocks_time_embed_dim,
451
- add_downsample=not is_final_block,
452
- resnet_eps=norm_eps,
453
- resnet_act_fn=act_fn,
454
- resnet_groups=norm_num_groups,
455
- cross_attention_dim=cross_attention_dim[i],
456
- num_attention_heads=num_attention_heads[i],
457
- downsample_padding=downsample_padding,
458
- dual_cross_attention=dual_cross_attention,
459
- use_linear_projection=use_linear_projection,
460
- only_cross_attention=only_cross_attention[i],
461
- upcast_attention=upcast_attention,
462
- resnet_time_scale_shift=resnet_time_scale_shift,
463
- attention_type=attention_type,
464
- resnet_skip_time_act=resnet_skip_time_act,
465
- resnet_out_scale_factor=resnet_out_scale_factor,
466
- cross_attention_norm=cross_attention_norm,
467
- attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
468
- dropout=dropout,
469
- )
470
- self.down_blocks.append(down_block)
471
-
472
- # mid
473
- if mid_block_type == "UNetMidBlock2DCrossAttn":
474
- self.mid_block = UNetMidBlock2DCrossAttn(
475
- transformer_layers_per_block=transformer_layers_per_block[-1],
476
- in_channels=block_out_channels[-1],
477
- temb_channels=blocks_time_embed_dim,
478
- dropout=dropout,
479
- resnet_eps=norm_eps,
480
- resnet_act_fn=act_fn,
481
- output_scale_factor=mid_block_scale_factor,
482
- resnet_time_scale_shift=resnet_time_scale_shift,
483
- cross_attention_dim=cross_attention_dim[-1],
484
- num_attention_heads=num_attention_heads[-1],
485
- resnet_groups=norm_num_groups,
486
- dual_cross_attention=dual_cross_attention,
487
- use_linear_projection=use_linear_projection,
488
- upcast_attention=upcast_attention,
489
- attention_type=attention_type,
490
- )
491
- elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
492
- self.mid_block = UNetMidBlock2DSimpleCrossAttn(
493
- in_channels=block_out_channels[-1],
494
- temb_channels=blocks_time_embed_dim,
495
- dropout=dropout,
496
- resnet_eps=norm_eps,
497
- resnet_act_fn=act_fn,
498
- output_scale_factor=mid_block_scale_factor,
499
- cross_attention_dim=cross_attention_dim[-1],
500
- attention_head_dim=attention_head_dim[-1],
501
- resnet_groups=norm_num_groups,
502
- resnet_time_scale_shift=resnet_time_scale_shift,
503
- skip_time_act=resnet_skip_time_act,
504
- only_cross_attention=mid_block_only_cross_attention,
505
- cross_attention_norm=cross_attention_norm,
506
- )
507
- elif mid_block_type == "UNetMidBlock2D":
508
- self.mid_block = UNetMidBlock2D(
509
- in_channels=block_out_channels[-1],
510
- temb_channels=blocks_time_embed_dim,
511
- dropout=dropout,
512
- num_layers=0,
513
- resnet_eps=norm_eps,
514
- resnet_act_fn=act_fn,
515
- output_scale_factor=mid_block_scale_factor,
516
- resnet_groups=norm_num_groups,
517
- resnet_time_scale_shift=resnet_time_scale_shift,
518
- add_attention=False,
519
- )
520
- elif mid_block_type is None:
521
- self.mid_block = None
522
- else:
523
- raise ValueError(f"unknown mid_block_type : {mid_block_type}")
524
-
525
- # count how many layers upsample the images
526
- self.num_upsamplers = 0
527
-
528
- # up
529
- reversed_block_out_channels = list(reversed(block_out_channels))
530
- reversed_num_attention_heads = list(reversed(num_attention_heads))
531
- reversed_layers_per_block = list(reversed(layers_per_block))
532
- reversed_cross_attention_dim = list(reversed(cross_attention_dim))
533
- reversed_transformer_layers_per_block = (
534
- list(reversed(transformer_layers_per_block))
535
- if reverse_transformer_layers_per_block is None
536
- else reverse_transformer_layers_per_block
537
- )
538
- only_cross_attention = list(reversed(only_cross_attention))
539
-
540
- output_channel = reversed_block_out_channels[0]
541
- for i, up_block_type in enumerate(up_block_types):
542
- is_final_block = i == len(block_out_channels) - 1
543
-
544
- prev_output_channel = output_channel
545
- output_channel = reversed_block_out_channels[i]
546
- input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
547
-
548
- # add upsample block for all BUT final layer
549
- if not is_final_block:
550
- add_upsample = True
551
- self.num_upsamplers += 1
552
- else:
553
- add_upsample = False
554
-
555
- up_block = get_up_block(
556
- up_block_type,
557
- num_layers=reversed_layers_per_block[i] + 1,
558
- transformer_layers_per_block=reversed_transformer_layers_per_block[i],
559
- in_channels=input_channel,
560
- out_channels=output_channel,
561
- prev_output_channel=prev_output_channel,
562
- temb_channels=blocks_time_embed_dim,
563
- add_upsample=add_upsample,
564
- resnet_eps=norm_eps,
565
- resnet_act_fn=act_fn,
566
- resolution_idx=i,
567
- resnet_groups=norm_num_groups,
568
- cross_attention_dim=reversed_cross_attention_dim[i],
569
- num_attention_heads=reversed_num_attention_heads[i],
570
- dual_cross_attention=dual_cross_attention,
571
- use_linear_projection=use_linear_projection,
572
- only_cross_attention=only_cross_attention[i],
573
- upcast_attention=upcast_attention,
574
- resnet_time_scale_shift=resnet_time_scale_shift,
575
- attention_type=attention_type,
576
- resnet_skip_time_act=resnet_skip_time_act,
577
- resnet_out_scale_factor=resnet_out_scale_factor,
578
- cross_attention_norm=cross_attention_norm,
579
- attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
580
- dropout=dropout,
581
- )
582
- self.up_blocks.append(up_block)
583
- prev_output_channel = output_channel
584
-
585
- # out
586
- if norm_num_groups is not None:
587
- self.conv_norm_out = nn.GroupNorm(
588
- num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
589
- )
590
-
591
- self.conv_act = get_activation(act_fn)
592
-
593
- else:
594
- self.conv_norm_out = None
595
- self.conv_act = None
596
-
597
- conv_out_padding = (conv_out_kernel - 1) // 2
598
- self.conv_out = nn.Conv2d(
599
- block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
600
- )
601
-
602
- if attention_type in ["gated", "gated-text-image"]:
603
- positive_len = 768
604
- if isinstance(cross_attention_dim, int):
605
- positive_len = cross_attention_dim
606
- elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list):
607
- positive_len = cross_attention_dim[0]
608
-
609
- feature_type = "text-only" if attention_type == "gated" else "text-image"
610
- self.position_net = GLIGENTextBoundingboxProjection(
611
- positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
612
- )
613
-
614
- def _set_gradient_checkpointing(self, module, value=False):
615
- if hasattr(module, "gradient_checkpointing"):
616
- module.gradient_checkpointing = value
617
-
618
- def forward(
619
- self,
620
- sample: torch.FloatTensor,
621
- additional_embd: torch.Tensor,
622
- timestep: Union[torch.Tensor, float, int],
623
- encoder_hidden_states: torch.Tensor,
624
- class_labels: Optional[torch.Tensor] = None,
625
- timestep_cond: Optional[torch.Tensor] = None,
626
- attention_mask: Optional[torch.Tensor] = None,
627
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
628
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
629
- down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
630
- mid_block_additional_residual: Optional[torch.Tensor] = None,
631
- down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
632
- encoder_attention_mask: Optional[torch.Tensor] = None,
633
- return_dict: bool = True,
634
- ) -> Union[UNet2DConditionOutput, Tuple]:
635
- r"""
636
- The [`UNet2DConditionModel`] forward method.
637
-
638
- Args:
639
- sample (`torch.FloatTensor`):
640
- The noisy input tensor with the following shape `(batch, channel, height, width)`.
641
- timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
642
- encoder_hidden_states (`torch.FloatTensor`):
643
- The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
644
- class_labels (`torch.Tensor`, *optional*, defaults to `None`):
645
- Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
646
- timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
647
- Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
648
- through the `self.time_embedding` layer to obtain the timestep embeddings.
649
- attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
650
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
651
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
652
- negative values to the attention scores corresponding to "discard" tokens.
653
- cross_attention_kwargs (`dict`, *optional*):
654
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
655
- `self.processor` in
656
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
657
- added_cond_kwargs: (`dict`, *optional*):
658
- A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
659
- are passed along to the UNet blocks.
660
- down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
661
- A tuple of tensors that if specified are added to the residuals of down unet blocks.
662
- mid_block_additional_residual: (`torch.Tensor`, *optional*):
663
- A tensor that if specified is added to the residual of the middle unet block.
664
- encoder_attention_mask (`torch.Tensor`):
665
- A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
666
- `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
667
- which adds large negative values to the attention scores corresponding to "discard" tokens.
668
- return_dict (`bool`, *optional*, defaults to `True`):
669
- Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
670
- tuple.
671
- cross_attention_kwargs (`dict`, *optional*):
672
- A kwargs dictionary that if specified is passed along to the [`AttnProcessor`].
673
- added_cond_kwargs: (`dict`, *optional*):
674
- A kwargs dictionary containin additional embeddings that if specified are added to the embeddings that
675
- are passed along to the UNet blocks.
676
- down_block_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
677
- additional residuals to be added to UNet long skip connections from down blocks to up blocks for
678
- example from ControlNet side model(s)
679
- mid_block_additional_residual (`torch.Tensor`, *optional*):
680
- additional residual to be added to UNet mid block output, for example from ControlNet side model
681
- down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
682
- additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
683
-
684
- Returns:
685
- [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
686
- If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned, otherwise
687
- a `tuple` is returned where the first element is the sample tensor.
688
- """
689
- # By default samples have to be AT least a multiple of the overall upsampling factor.
690
- # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
691
- # However, the upsampling interpolation output size can be forced to fit any upsampling size
692
- # on the fly if necessary.
693
- default_overall_up_factor = 2**self.num_upsamplers
694
-
695
- # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
696
- forward_upsample_size = False
697
- upsample_size = None
698
-
699
- for dim in sample.shape[-2:]:
700
- if dim % default_overall_up_factor != 0:
701
- # Forward upsample size to force interpolation output size.
702
- forward_upsample_size = True
703
- break
704
-
705
- # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
706
- # expects mask of shape:
707
- # [batch, key_tokens]
708
- # adds singleton query_tokens dimension:
709
- # [batch, 1, key_tokens]
710
- # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
711
- # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
712
- # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
713
- if attention_mask is not None:
714
- # assume that mask is expressed as:
715
- # (1 = keep, 0 = discard)
716
- # convert mask into a bias that can be added to attention scores:
717
- # (keep = +0, discard = -10000.0)
718
- attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
719
- attention_mask = attention_mask.unsqueeze(1)
720
-
721
- # convert encoder_attention_mask to a bias the same way we do for attention_mask
722
- if encoder_attention_mask is not None:
723
- encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
724
- encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
725
-
726
- # 0. center input if necessary
727
- if self.config.center_input_sample:
728
- sample = 2 * sample - 1.0
729
-
730
- # 1. time
731
- timesteps = timestep
732
- if not torch.is_tensor(timesteps):
733
- # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
734
- # This would be a good case for the `match` statement (Python 3.10+)
735
- is_mps = sample.device.type == "mps"
736
- if isinstance(timestep, float):
737
- dtype = torch.float32 if is_mps else torch.float64
738
- else:
739
- dtype = torch.int32 if is_mps else torch.int64
740
- timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
741
- elif len(timesteps.shape) == 0:
742
- timesteps = timesteps[None].to(sample.device)
743
-
744
- # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
745
- timesteps = timesteps.expand(sample.shape[0])
746
-
747
- t_emb = self.time_proj(timesteps)
748
-
749
- # `Timesteps` does not contain any weights and will always return f32 tensors
750
- # but time_embedding might actually be running in fp16. so we need to cast here.
751
- # there might be better ways to encapsulate this.
752
- t_emb = t_emb.to(dtype=sample.dtype)
753
-
754
- emb = self.time_embedding(t_emb, timestep_cond)
755
- aug_emb = None
756
-
757
- if self.class_embedding is not None:
758
- if class_labels is None:
759
- raise ValueError("class_labels should be provided when num_class_embeds > 0")
760
-
761
- if self.config.class_embed_type == "timestep":
762
- class_labels = self.time_proj(class_labels)
763
-
764
- # `Timesteps` does not contain any weights and will always return f32 tensors
765
- # there might be better ways to encapsulate this.
766
- class_labels = class_labels.to(dtype=sample.dtype)
767
-
768
- class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
769
-
770
- if self.config.class_embeddings_concat:
771
- emb = torch.cat([emb, class_emb], dim=-1)
772
- else:
773
- emb = emb + class_emb
774
-
775
- if self.config.addition_embed_type == "text":
776
- aug_emb = self.add_embedding(encoder_hidden_states)
777
- elif self.config.addition_embed_type == "text_image":
778
- # Kandinsky 2.1 - style
779
- if "image_embeds" not in added_cond_kwargs:
780
- raise ValueError(
781
- f"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
782
- )
783
-
784
- image_embs = added_cond_kwargs.get("image_embeds")
785
- text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
786
- aug_emb = self.add_embedding(text_embs, image_embs)
787
- elif self.config.addition_embed_type == "text_time":
788
- # SDXL - style
789
- if "text_embeds" not in added_cond_kwargs:
790
- raise ValueError(
791
- f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
792
- )
793
- text_embeds = added_cond_kwargs.get("text_embeds")
794
- if "time_ids" not in added_cond_kwargs:
795
- raise ValueError(
796
- f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
797
- )
798
- time_ids = added_cond_kwargs.get("time_ids")
799
- time_embeds = self.add_time_proj(time_ids.flatten())
800
- time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
801
- add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
802
- add_embeds = add_embeds.to(emb.dtype)
803
- aug_emb = self.add_embedding(add_embeds)
804
- elif self.config.addition_embed_type == "image":
805
- # Kandinsky 2.2 - style
806
- if "image_embeds" not in added_cond_kwargs:
807
- raise ValueError(
808
- f"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
809
- )
810
- image_embs = added_cond_kwargs.get("image_embeds")
811
- aug_emb = self.add_embedding(image_embs)
812
- elif self.config.addition_embed_type == "image_hint":
813
- # Kandinsky 2.2 - style
814
- if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs:
815
- raise ValueError(
816
- f"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`"
817
- )
818
- image_embs = added_cond_kwargs.get("image_embeds")
819
- hint = added_cond_kwargs.get("hint")
820
- aug_emb, hint = self.add_embedding(image_embs, hint)
821
- sample = torch.cat([sample, hint], dim=1)
822
-
823
- emb = emb + aug_emb if aug_emb is not None else emb
824
-
825
- if self.time_embed_act is not None:
826
- emb = self.time_embed_act(emb)
827
-
828
- emb = emb + additional_embd
829
-
830
- if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
831
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
832
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
833
- # Kadinsky 2.1 - style
834
- if "image_embeds" not in added_cond_kwargs:
835
- raise ValueError(
836
- f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
837
- )
838
-
839
- image_embeds = added_cond_kwargs.get("image_embeds")
840
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
841
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
842
- # Kandinsky 2.2 - style
843
- if "image_embeds" not in added_cond_kwargs:
844
- raise ValueError(
845
- f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
846
- )
847
- image_embeds = added_cond_kwargs.get("image_embeds")
848
- encoder_hidden_states = self.encoder_hid_proj(image_embeds)
849
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
850
- if "image_embeds" not in added_cond_kwargs:
851
- raise ValueError(
852
- f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
853
- )
854
- image_embeds = added_cond_kwargs.get("image_embeds")
855
- image_embeds = self.encoder_hid_proj(image_embeds)
856
- encoder_hidden_states = (encoder_hidden_states, image_embeds)
857
-
858
- # 2. pre-process
859
- sample = self.conv_in(sample)
860
-
861
- # 2.5 GLIGEN position net
862
- if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
863
- cross_attention_kwargs = cross_attention_kwargs.copy()
864
- gligen_args = cross_attention_kwargs.pop("gligen")
865
- cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
866
-
867
- # 3. down
868
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
869
- if USE_PEFT_BACKEND:
870
- # weight the lora layers by setting `lora_scale` for each PEFT layer
871
- scale_lora_layers(self, lora_scale)
872
-
873
- is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
874
- # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
875
- is_adapter = down_intrablock_additional_residuals is not None
876
- # maintain backward compatibility for legacy usage, where
877
- # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
878
- # but can only use one or the other
879
- if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
880
- deprecate(
881
- "T2I should not use down_block_additional_residuals",
882
- "1.3.0",
883
- "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
884
- and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
885
- for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
886
- standard_warn=False,
887
- )
888
- down_intrablock_additional_residuals = down_block_additional_residuals
889
- is_adapter = True
890
-
891
- down_block_res_samples = (sample,)
892
- for downsample_block in self.down_blocks:
893
- if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
894
- # For t2i-adapter CrossAttnDownBlock2D
895
- additional_residuals = {}
896
- if is_adapter and len(down_intrablock_additional_residuals) > 0:
897
- additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
898
-
899
- sample, res_samples = downsample_block(
900
- hidden_states=sample,
901
- temb=emb,
902
- encoder_hidden_states=encoder_hidden_states,
903
- attention_mask=attention_mask,
904
- cross_attention_kwargs=cross_attention_kwargs,
905
- encoder_attention_mask=encoder_attention_mask,
906
- **additional_residuals,
907
- )
908
- else:
909
- sample, res_samples = downsample_block(hidden_states=sample, temb=emb, scale=lora_scale)
910
- if is_adapter and len(down_intrablock_additional_residuals) > 0:
911
- sample += down_intrablock_additional_residuals.pop(0)
912
-
913
- down_block_res_samples += res_samples
914
-
915
- if is_controlnet:
916
- new_down_block_res_samples = ()
917
-
918
- for down_block_res_sample, down_block_additional_residual in zip(
919
- down_block_res_samples, down_block_additional_residuals
920
- ):
921
- down_block_res_sample = down_block_res_sample + down_block_additional_residual
922
- new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
923
-
924
- down_block_res_samples = new_down_block_res_samples
925
-
926
- # 4. mid
927
- if self.mid_block is not None:
928
- if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
929
- sample = self.mid_block(
930
- sample,
931
- emb,
932
- encoder_hidden_states=encoder_hidden_states,
933
- attention_mask=attention_mask,
934
- cross_attention_kwargs=cross_attention_kwargs,
935
- encoder_attention_mask=encoder_attention_mask,
936
- )
937
- else:
938
- sample = self.mid_block(sample, emb)
939
-
940
- # To support T2I-Adapter-XL
941
- if (
942
- is_adapter
943
- and len(down_intrablock_additional_residuals) > 0
944
- and sample.shape == down_intrablock_additional_residuals[0].shape
945
- ):
946
- sample += down_intrablock_additional_residuals.pop(0)
947
-
948
- if is_controlnet:
949
- sample = sample + mid_block_additional_residual
950
-
951
- # 5. up
952
- for i, upsample_block in enumerate(self.up_blocks):
953
- is_final_block = i == len(self.up_blocks) - 1
954
-
955
- res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
956
- down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
957
-
958
- # if we have not reached the final block and need to forward the
959
- # upsample size, we do it here
960
- if not is_final_block and forward_upsample_size:
961
- upsample_size = down_block_res_samples[-1].shape[2:]
962
-
963
- if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
964
- sample = upsample_block(
965
- hidden_states=sample,
966
- temb=emb,
967
- res_hidden_states_tuple=res_samples,
968
- encoder_hidden_states=encoder_hidden_states,
969
- cross_attention_kwargs=cross_attention_kwargs,
970
- upsample_size=upsample_size,
971
- attention_mask=attention_mask,
972
- encoder_attention_mask=encoder_attention_mask,
973
- )
974
- else:
975
- sample = upsample_block(
976
- hidden_states=sample,
977
- temb=emb,
978
- res_hidden_states_tuple=res_samples,
979
- upsample_size=upsample_size,
980
- scale=lora_scale,
981
- )
982
-
983
- # 6. post-process
984
- if self.conv_norm_out:
985
- sample = self.conv_norm_out(sample)
986
- sample = self.conv_act(sample)
987
- sample = self.conv_out(sample)
988
-
989
- if USE_PEFT_BACKEND:
990
- # remove `lora_scale` from each PEFT layer
991
- unscale_lora_layers(self, lora_scale)
992
-
993
- if not return_dict:
994
- return (sample,)
995
-
996
- return UNet2DConditionOutput(sample=sample)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models/unet_2d_condition_flow.py DELETED
@@ -1,934 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from dataclasses import dataclass
15
- from typing import Any, Dict, List, Optional, Tuple, Union
16
- import math
17
-
18
- import torch
19
- import torch.nn as nn
20
- import torch.utils.checkpoint
21
-
22
- from diffusers.configuration_utils import ConfigMixin, register_to_config
23
- from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
24
- from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
25
- from diffusers.models.activations import get_activation
26
- from diffusers.models.embeddings import (
27
- GaussianFourierProjection,
28
- GLIGENTextBoundingboxProjection,
29
- ImageHintTimeEmbedding,
30
- ImageProjection,
31
- ImageTimeEmbedding,
32
- TextImageProjection,
33
- TextImageTimeEmbedding,
34
- TextTimeEmbedding,
35
- TimestepEmbedding,
36
- Timesteps,
37
- )
38
- from diffusers.models.modeling_utils import ModelMixin
39
- from diffusers.models.unet_2d_blocks import (
40
- UNetMidBlock2D,
41
- UNetMidBlock2DCrossAttn,
42
- UNetMidBlock2DSimpleCrossAttn,
43
- get_down_block,
44
- get_up_block,
45
- )
46
-
47
-
48
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
-
50
-
51
- @dataclass
52
- class UNet2DConditionOutput(BaseOutput):
53
- """
54
- The output of [`UNet2DConditionModel`].
55
-
56
- Args:
57
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
58
- The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
59
- """
60
-
61
- sample: torch.FloatTensor = None
62
-
63
-
64
- class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin):
65
- r"""
66
- A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
67
- shaped output.
68
-
69
- This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
70
- for all models (such as downloading or saving).
71
-
72
- Parameters:
73
- sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
74
- Height and width of input/output sample.
75
- in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
76
- out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
77
- center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
78
- flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
79
- Whether to flip the sin to cos in the time embedding.
80
- freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
81
- down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
82
- The tuple of downsample blocks to use.
83
- mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
84
- Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
85
- `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
86
- up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
87
- The tuple of upsample blocks to use.
88
- only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
89
- Whether to include self-attention in the basic transformer blocks, see
90
- [`~models.attention.BasicTransformerBlock`].
91
- block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
92
- The tuple of output channels for each block.
93
- layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
94
- downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
95
- mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
96
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
97
- act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
98
- norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
99
- If `None`, normalization and activation layers is skipped in post-processing.
100
- norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
101
- cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
102
- The dimension of the cross attention features.
103
- transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
104
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
105
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
106
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
107
- reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
108
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
109
- blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
110
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
111
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
112
- encoder_hid_dim (`int`, *optional*, defaults to None):
113
- If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
114
- dimension to `cross_attention_dim`.
115
- encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
116
- If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
117
- embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
118
- attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
119
- num_attention_heads (`int`, *optional*):
120
- The number of attention heads. If not defined, defaults to `attention_head_dim`
121
- resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
122
- for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
123
- class_embed_type (`str`, *optional*, defaults to `None`):
124
- The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
125
- `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
126
- addition_embed_type (`str`, *optional*, defaults to `None`):
127
- Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
128
- "text". "text" will use the `TextTimeEmbedding` layer.
129
- addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
130
- Dimension for the timestep embeddings.
131
- num_class_embeds (`int`, *optional*, defaults to `None`):
132
- Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
133
- class conditioning with `class_embed_type` equal to `None`.
134
- time_embedding_type (`str`, *optional*, defaults to `positional`):
135
- The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
136
- time_embedding_dim (`int`, *optional*, defaults to `None`):
137
- An optional override for the dimension of the projected time embedding.
138
- time_embedding_act_fn (`str`, *optional*, defaults to `None`):
139
- Optional activation function to use only once on the time embeddings before they are passed to the rest of
140
- the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
141
- timestep_post_act (`str`, *optional*, defaults to `None`):
142
- The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
143
- time_cond_proj_dim (`int`, *optional*, defaults to `None`):
144
- The dimension of `cond_proj` layer in the timestep embedding.
145
- conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`,
146
- *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`,
147
- *optional*): The dimension of the `class_labels` input when
148
- `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
149
- class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
150
- embeddings with the class embeddings.
151
- mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
152
- Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
153
- `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
154
- `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
155
- otherwise.
156
- """
157
-
158
- _supports_gradient_checkpointing = True
159
-
160
- @register_to_config
161
- def __init__(
162
- self,
163
- sample_size: Optional[int] = None,
164
- in_channels: int = 4,
165
- out_channels: int = 4,
166
- center_input_sample: bool = False,
167
- flip_sin_to_cos: bool = True,
168
- freq_shift: int = 0,
169
- down_block_types: Tuple[str] = (
170
- "CrossAttnDownBlock2D",
171
- "CrossAttnDownBlock2D",
172
- "CrossAttnDownBlock2D",
173
- "DownBlock2D",
174
- ),
175
- mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
176
- up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
177
- only_cross_attention: Union[bool, Tuple[bool]] = False,
178
- block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
179
- layers_per_block: Union[int, Tuple[int]] = 2,
180
- downsample_padding: int = 1,
181
- mid_block_scale_factor: float = 1,
182
- dropout: float = 0.0,
183
- act_fn: str = "silu",
184
- norm_num_groups: Optional[int] = 32,
185
- norm_eps: float = 1e-5,
186
- cross_attention_dim: Union[int, Tuple[int]] = 1280,
187
- transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
188
- reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
189
- encoder_hid_dim: Optional[int] = None,
190
- encoder_hid_dim_type: Optional[str] = None,
191
- attention_head_dim: Union[int, Tuple[int]] = 8,
192
- num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
193
- dual_cross_attention: bool = False,
194
- use_linear_projection: bool = False,
195
- class_embed_type: Optional[str] = None,
196
- addition_embed_type: Optional[str] = None,
197
- addition_time_embed_dim: Optional[int] = None,
198
- num_class_embeds: Optional[int] = None,
199
- upcast_attention: bool = False,
200
- resnet_time_scale_shift: str = "default",
201
- resnet_skip_time_act: bool = False,
202
- resnet_out_scale_factor: int = 1.0,
203
- time_embedding_type: str = "positional",
204
- time_embedding_dim: Optional[int] = None,
205
- time_embedding_act_fn: Optional[str] = None,
206
- timestep_post_act: Optional[str] = None,
207
- time_cond_proj_dim: Optional[int] = None,
208
- conv_in_kernel: int = 3,
209
- conv_out_kernel: int = 3,
210
- projection_class_embeddings_input_dim: Optional[int] = None,
211
- attention_type: str = "default",
212
- class_embeddings_concat: bool = False,
213
- mid_block_only_cross_attention: Optional[bool] = None,
214
- cross_attention_norm: Optional[str] = None,
215
- addition_embed_type_num_heads=64,
216
- ):
217
- super().__init__()
218
-
219
- self.sample_size = sample_size
220
- self.block_out_channels = block_out_channels
221
-
222
- if num_attention_heads is not None:
223
- raise ValueError(
224
- "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19."
225
- )
226
-
227
- # If `num_attention_heads` is not defined (which is the case for most models)
228
- # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
229
- # The reason for this behavior is to correct for incorrectly named variables that were introduced
230
- # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
231
- # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
232
- # which is why we correct for the naming here.
233
- num_attention_heads = num_attention_heads or attention_head_dim
234
-
235
- # Check inputs
236
- if len(down_block_types) != len(up_block_types):
237
- raise ValueError(
238
- f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
239
- )
240
-
241
- if len(block_out_channels) != len(down_block_types):
242
- raise ValueError(
243
- f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
244
- )
245
-
246
- if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
247
- raise ValueError(
248
- f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
249
- )
250
-
251
- if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
252
- raise ValueError(
253
- f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
254
- )
255
-
256
- if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
257
- raise ValueError(
258
- f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
259
- )
260
-
261
- if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
262
- raise ValueError(
263
- f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
264
- )
265
-
266
- if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
267
- raise ValueError(
268
- f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
269
- )
270
- if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
271
- for layer_number_per_block in transformer_layers_per_block:
272
- if isinstance(layer_number_per_block, list):
273
- raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
274
-
275
- # input
276
- conv_in_padding = (conv_in_kernel - 1) // 2
277
- self.conv_in = nn.Conv2d(
278
- in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
279
- )
280
-
281
- # time
282
- if time_embedding_type == "fourier":
283
- time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
284
- if time_embed_dim % 2 != 0:
285
- raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
286
- self.time_proj = GaussianFourierProjection(
287
- time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
288
- )
289
- timestep_input_dim = time_embed_dim
290
- elif time_embedding_type == "positional":
291
- time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
292
-
293
- self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
294
- timestep_input_dim = block_out_channels[0]
295
- else:
296
- raise ValueError(
297
- f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
298
- )
299
-
300
- self.time_embedding = TimestepEmbedding(
301
- timestep_input_dim,
302
- time_embed_dim,
303
- act_fn=act_fn,
304
- post_act_fn=timestep_post_act,
305
- cond_proj_dim=time_cond_proj_dim,
306
- )
307
-
308
- if encoder_hid_dim_type is None and encoder_hid_dim is not None:
309
- encoder_hid_dim_type = "text_proj"
310
- self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
311
- logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
312
-
313
- if encoder_hid_dim is None and encoder_hid_dim_type is not None:
314
- raise ValueError(
315
- f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
316
- )
317
-
318
- if encoder_hid_dim_type == "text_proj":
319
- self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
320
- elif encoder_hid_dim_type == "text_image_proj":
321
- # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
322
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
323
- # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
324
- self.encoder_hid_proj = TextImageProjection(
325
- text_embed_dim=encoder_hid_dim,
326
- image_embed_dim=cross_attention_dim,
327
- cross_attention_dim=cross_attention_dim,
328
- )
329
- elif encoder_hid_dim_type == "image_proj":
330
- # Kandinsky 2.2
331
- self.encoder_hid_proj = ImageProjection(
332
- image_embed_dim=encoder_hid_dim,
333
- cross_attention_dim=cross_attention_dim,
334
- )
335
- elif encoder_hid_dim_type is not None:
336
- raise ValueError(
337
- f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
338
- )
339
- else:
340
- self.encoder_hid_proj = None
341
-
342
- # class embedding
343
- if class_embed_type is None and num_class_embeds is not None:
344
- self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
345
- elif class_embed_type == "timestep":
346
- self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
347
- elif class_embed_type == "identity":
348
- self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
349
- elif class_embed_type == "projection":
350
- if projection_class_embeddings_input_dim is None:
351
- raise ValueError(
352
- "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
353
- )
354
- # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
355
- # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
356
- # 2. it projects from an arbitrary input dimension.
357
- #
358
- # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
359
- # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
360
- # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
361
- self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
362
- elif class_embed_type == "simple_projection":
363
- if projection_class_embeddings_input_dim is None:
364
- raise ValueError(
365
- "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
366
- )
367
- self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
368
- else:
369
- self.class_embedding = None
370
-
371
- if addition_embed_type == "text":
372
- if encoder_hid_dim is not None:
373
- text_time_embedding_from_dim = encoder_hid_dim
374
- else:
375
- text_time_embedding_from_dim = cross_attention_dim
376
-
377
- self.add_embedding = TextTimeEmbedding(
378
- text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
379
- )
380
- elif addition_embed_type == "text_image":
381
- # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
382
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
383
- # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
384
- self.add_embedding = TextImageTimeEmbedding(
385
- text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
386
- )
387
- elif addition_embed_type == "text_time":
388
- self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
389
- self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
390
- elif addition_embed_type == "image":
391
- # Kandinsky 2.2
392
- self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
393
- elif addition_embed_type == "image_hint":
394
- # Kandinsky 2.2 ControlNet
395
- self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
396
- elif addition_embed_type is not None:
397
- raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
398
-
399
- if time_embedding_act_fn is None:
400
- self.time_embed_act = None
401
- else:
402
- self.time_embed_act = get_activation(time_embedding_act_fn)
403
-
404
- self.down_blocks = nn.ModuleList([])
405
- self.up_blocks = nn.ModuleList([])
406
-
407
- if isinstance(only_cross_attention, bool):
408
- if mid_block_only_cross_attention is None:
409
- mid_block_only_cross_attention = only_cross_attention
410
-
411
- only_cross_attention = [only_cross_attention] * len(down_block_types)
412
-
413
- if mid_block_only_cross_attention is None:
414
- mid_block_only_cross_attention = False
415
-
416
- if isinstance(num_attention_heads, int):
417
- num_attention_heads = (num_attention_heads,) * len(down_block_types)
418
-
419
- if isinstance(attention_head_dim, int):
420
- attention_head_dim = (attention_head_dim,) * len(down_block_types)
421
-
422
- if isinstance(cross_attention_dim, int):
423
- cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
424
-
425
- if isinstance(layers_per_block, int):
426
- layers_per_block = [layers_per_block] * len(down_block_types)
427
-
428
- if isinstance(transformer_layers_per_block, int):
429
- transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
430
-
431
- if class_embeddings_concat:
432
- # The time embeddings are concatenated with the class embeddings. The dimension of the
433
- # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
434
- # regular time embeddings
435
- blocks_time_embed_dim = time_embed_dim * 2
436
- else:
437
- blocks_time_embed_dim = time_embed_dim
438
-
439
- # down
440
- output_channel = block_out_channels[0]
441
- for i, down_block_type in enumerate(down_block_types):
442
- input_channel = output_channel
443
- output_channel = block_out_channels[i]
444
- is_final_block = i == len(block_out_channels) - 1
445
-
446
- down_block = get_down_block(
447
- down_block_type,
448
- num_layers=layers_per_block[i],
449
- transformer_layers_per_block=transformer_layers_per_block[i],
450
- in_channels=input_channel,
451
- out_channels=output_channel,
452
- temb_channels=blocks_time_embed_dim,
453
- add_downsample=not is_final_block,
454
- resnet_eps=norm_eps,
455
- resnet_act_fn=act_fn,
456
- resnet_groups=norm_num_groups,
457
- cross_attention_dim=cross_attention_dim[i],
458
- num_attention_heads=num_attention_heads[i],
459
- downsample_padding=downsample_padding,
460
- dual_cross_attention=dual_cross_attention,
461
- use_linear_projection=use_linear_projection,
462
- only_cross_attention=only_cross_attention[i],
463
- upcast_attention=upcast_attention,
464
- resnet_time_scale_shift=resnet_time_scale_shift,
465
- attention_type=attention_type,
466
- resnet_skip_time_act=resnet_skip_time_act,
467
- resnet_out_scale_factor=resnet_out_scale_factor,
468
- cross_attention_norm=cross_attention_norm,
469
- attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
470
- dropout=dropout,
471
- )
472
- self.down_blocks.append(down_block)
473
-
474
- # mid
475
- if mid_block_type == "UNetMidBlock2DCrossAttn":
476
- self.mid_block = UNetMidBlock2DCrossAttn(
477
- transformer_layers_per_block=transformer_layers_per_block[-1],
478
- in_channels=block_out_channels[-1],
479
- temb_channels=blocks_time_embed_dim,
480
- dropout=dropout,
481
- resnet_eps=norm_eps,
482
- resnet_act_fn=act_fn,
483
- output_scale_factor=mid_block_scale_factor,
484
- resnet_time_scale_shift=resnet_time_scale_shift,
485
- cross_attention_dim=cross_attention_dim[-1],
486
- num_attention_heads=num_attention_heads[-1],
487
- resnet_groups=norm_num_groups,
488
- dual_cross_attention=dual_cross_attention,
489
- use_linear_projection=use_linear_projection,
490
- upcast_attention=upcast_attention,
491
- attention_type=attention_type,
492
- )
493
- elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
494
- self.mid_block = UNetMidBlock2DSimpleCrossAttn(
495
- in_channels=block_out_channels[-1],
496
- temb_channels=blocks_time_embed_dim,
497
- dropout=dropout,
498
- resnet_eps=norm_eps,
499
- resnet_act_fn=act_fn,
500
- output_scale_factor=mid_block_scale_factor,
501
- cross_attention_dim=cross_attention_dim[-1],
502
- attention_head_dim=attention_head_dim[-1],
503
- resnet_groups=norm_num_groups,
504
- resnet_time_scale_shift=resnet_time_scale_shift,
505
- skip_time_act=resnet_skip_time_act,
506
- only_cross_attention=mid_block_only_cross_attention,
507
- cross_attention_norm=cross_attention_norm,
508
- )
509
- elif mid_block_type == "UNetMidBlock2D":
510
- self.mid_block = UNetMidBlock2D(
511
- in_channels=block_out_channels[-1],
512
- temb_channels=blocks_time_embed_dim,
513
- dropout=dropout,
514
- num_layers=0,
515
- resnet_eps=norm_eps,
516
- resnet_act_fn=act_fn,
517
- output_scale_factor=mid_block_scale_factor,
518
- resnet_groups=norm_num_groups,
519
- resnet_time_scale_shift=resnet_time_scale_shift,
520
- add_attention=False,
521
- )
522
- elif mid_block_type is None:
523
- self.mid_block = None
524
- else:
525
- raise ValueError(f"unknown mid_block_type : {mid_block_type}")
526
-
527
- # count how many layers upsample the images
528
- self.num_upsamplers = 0
529
-
530
- # up
531
- reversed_block_out_channels = list(reversed(block_out_channels))
532
- reversed_num_attention_heads = list(reversed(num_attention_heads))
533
- reversed_layers_per_block = list(reversed(layers_per_block))
534
- reversed_cross_attention_dim = list(reversed(cross_attention_dim))
535
- reversed_transformer_layers_per_block = (
536
- list(reversed(transformer_layers_per_block))
537
- if reverse_transformer_layers_per_block is None
538
- else reverse_transformer_layers_per_block
539
- )
540
- only_cross_attention = list(reversed(only_cross_attention))
541
-
542
- output_channel = reversed_block_out_channels[0]
543
- for i, up_block_type in enumerate(up_block_types):
544
- is_final_block = i == len(block_out_channels) - 1
545
-
546
- prev_output_channel = output_channel
547
- output_channel = reversed_block_out_channels[i]
548
- input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
549
-
550
- # add upsample block for all BUT final layer
551
- if not is_final_block:
552
- add_upsample = True
553
- self.num_upsamplers += 1
554
- else:
555
- add_upsample = False
556
-
557
- up_block = get_up_block(
558
- up_block_type,
559
- num_layers=reversed_layers_per_block[i] + 1,
560
- transformer_layers_per_block=reversed_transformer_layers_per_block[i],
561
- in_channels=input_channel,
562
- out_channels=output_channel,
563
- prev_output_channel=prev_output_channel,
564
- temb_channels=blocks_time_embed_dim,
565
- add_upsample=add_upsample,
566
- resnet_eps=norm_eps,
567
- resnet_act_fn=act_fn,
568
- resolution_idx=i,
569
- resnet_groups=norm_num_groups,
570
- cross_attention_dim=reversed_cross_attention_dim[i],
571
- num_attention_heads=reversed_num_attention_heads[i],
572
- dual_cross_attention=dual_cross_attention,
573
- use_linear_projection=use_linear_projection,
574
- only_cross_attention=only_cross_attention[i],
575
- upcast_attention=upcast_attention,
576
- resnet_time_scale_shift=resnet_time_scale_shift,
577
- attention_type=attention_type,
578
- resnet_skip_time_act=resnet_skip_time_act,
579
- resnet_out_scale_factor=resnet_out_scale_factor,
580
- cross_attention_norm=cross_attention_norm,
581
- attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
582
- dropout=dropout,
583
- )
584
- self.up_blocks.append(up_block)
585
- prev_output_channel = output_channel
586
-
587
- # out
588
- if norm_num_groups is not None:
589
- self.conv_norm_out = nn.GroupNorm(
590
- num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
591
- )
592
-
593
- self.conv_act = get_activation(act_fn)
594
-
595
- else:
596
- self.conv_norm_out = None
597
- self.conv_act = None
598
-
599
- conv_out_padding = (conv_out_kernel - 1) // 2
600
- self.conv_out = nn.Conv2d(
601
- block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
602
- )
603
-
604
- if attention_type in ["gated", "gated-text-image"]:
605
- positive_len = 768
606
- if isinstance(cross_attention_dim, int):
607
- positive_len = cross_attention_dim
608
- elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list):
609
- positive_len = cross_attention_dim[0]
610
-
611
- feature_type = "text-only" if attention_type == "gated" else "text-image"
612
- self.position_net = GLIGENTextBoundingboxProjection(
613
- positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
614
- )
615
-
616
- def _set_gradient_checkpointing(self, module, value=False):
617
- if hasattr(module, "gradient_checkpointing"):
618
- module.gradient_checkpointing = value
619
-
620
- # https://github.com/atong01/conditional-flow-matching/blob/main/torchcfm/models/unet/nn.py#L87
621
- def timestep_embedding(self, timesteps, max_period=10000, scale=1000):
622
- """Create sinusoidal timestep embeddings.
623
-
624
- :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional.
625
- :param dim: the dimension of the output.
626
- :param max_period: controls the minimum frequency of the embeddings.
627
- :return: an [N x dim] Tensor of positional embeddings.
628
- """
629
- dim = self.block_out_channels[-1]
630
- half = dim // 2
631
- freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, device=timesteps.device) / half).type(timesteps.type())
632
- args = timesteps[:, None] * freqs[None] * scale
633
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
634
- if dim % 2:
635
- embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
636
- return embedding
637
-
638
- def forward(
639
- self,
640
- sample: torch.FloatTensor,
641
- timestep: Union[torch.Tensor, float, int],
642
- encoder_hidden_states: torch.Tensor,
643
- class_labels: Optional[torch.Tensor] = None,
644
- timestep_cond: Optional[torch.Tensor] = None,
645
- attention_mask: Optional[torch.Tensor] = None,
646
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
647
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
648
- down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
649
- mid_block_additional_residual: Optional[torch.Tensor] = None,
650
- down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
651
- encoder_attention_mask: Optional[torch.Tensor] = None,
652
- return_dict: bool = True,
653
- ) -> Union[UNet2DConditionOutput, Tuple]:
654
- r"""
655
- The [`UNet2DConditionModel`] forward method.
656
-
657
- Args:
658
- sample (`torch.FloatTensor`):
659
- The noisy input tensor with the following shape `(batch, channel, height, width)`.
660
- timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
661
- encoder_hidden_states (`torch.FloatTensor`):
662
- The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
663
- class_labels (`torch.Tensor`, *optional*, defaults to `None`):
664
- Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
665
- timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
666
- Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
667
- through the `self.time_embedding` layer to obtain the timestep embeddings.
668
- attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
669
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
670
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
671
- negative values to the attention scores corresponding to "discard" tokens.
672
- cross_attention_kwargs (`dict`, *optional*):
673
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
674
- `self.processor` in
675
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
676
- added_cond_kwargs: (`dict`, *optional*):
677
- A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
678
- are passed along to the UNet blocks.
679
- down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
680
- A tuple of tensors that if specified are added to the residuals of down unet blocks.
681
- mid_block_additional_residual: (`torch.Tensor`, *optional*):
682
- A tensor that if specified is added to the residual of the middle unet block.
683
- encoder_attention_mask (`torch.Tensor`):
684
- A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
685
- `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
686
- which adds large negative values to the attention scores corresponding to "discard" tokens.
687
- return_dict (`bool`, *optional*, defaults to `True`):
688
- Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
689
- tuple.
690
- cross_attention_kwargs (`dict`, *optional*):
691
- A kwargs dictionary that if specified is passed along to the [`AttnProcessor`].
692
- added_cond_kwargs: (`dict`, *optional*):
693
- A kwargs dictionary containin additional embeddings that if specified are added to the embeddings that
694
- are passed along to the UNet blocks.
695
- down_block_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
696
- additional residuals to be added to UNet long skip connections from down blocks to up blocks for
697
- example from ControlNet side model(s)
698
- mid_block_additional_residual (`torch.Tensor`, *optional*):
699
- additional residual to be added to UNet mid block output, for example from ControlNet side model
700
- down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
701
- additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
702
-
703
- Returns:
704
- [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
705
- If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned, otherwise
706
- a `tuple` is returned where the first element is the sample tensor.
707
- """
708
- # By default samples have to be AT least a multiple of the overall upsampling factor.
709
- # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
710
- # However, the upsampling interpolation output size can be forced to fit any upsampling size
711
- # on the fly if necessary.
712
- default_overall_up_factor = 2**self.num_upsamplers
713
-
714
- # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
715
- forward_upsample_size = False
716
- upsample_size = None
717
-
718
- for dim in sample.shape[-2:]:
719
- if dim % default_overall_up_factor != 0:
720
- # Forward upsample size to force interpolation output size.
721
- forward_upsample_size = True
722
- break
723
-
724
- # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
725
- # expects mask of shape:
726
- # [batch, key_tokens]
727
- # adds singleton query_tokens dimension:
728
- # [batch, 1, key_tokens]
729
- # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
730
- # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
731
- # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
732
- if attention_mask is not None:
733
- # assume that mask is expressed as:
734
- # (1 = keep, 0 = discard)
735
- # convert mask into a bias that can be added to attention scores:
736
- # (keep = +0, discard = -10000.0)
737
- attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
738
- attention_mask = attention_mask.unsqueeze(1)
739
-
740
- # convert encoder_attention_mask to a bias the same way we do for attention_mask
741
- if encoder_attention_mask is not None:
742
- encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
743
- encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
744
-
745
- # 0. center input if necessary
746
- if self.config.center_input_sample:
747
- sample = 2 * sample - 1.0
748
-
749
- # 1. time
750
- timesteps = timestep
751
- if not torch.is_tensor(timesteps):
752
- # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
753
- # This would be a good case for the `match` statement (Python 3.10+)
754
- is_mps = sample.device.type == "mps"
755
- if isinstance(timestep, float):
756
- dtype = torch.float32 if is_mps else torch.float64
757
- else:
758
- dtype = torch.int32 if is_mps else torch.int64
759
- timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
760
- elif len(timesteps.shape) == 0:
761
- timesteps = timesteps[None].to(sample.device)
762
-
763
- # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
764
- timesteps = timesteps.expand(sample.shape[0])
765
-
766
- emb = self.timestep_embedding(timesteps)
767
-
768
- if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
769
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
770
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
771
- # Kadinsky 2.1 - style
772
- if "image_embeds" not in added_cond_kwargs:
773
- raise ValueError(
774
- f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
775
- )
776
-
777
- image_embeds = added_cond_kwargs.get("image_embeds")
778
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
779
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
780
- # Kandinsky 2.2 - style
781
- if "image_embeds" not in added_cond_kwargs:
782
- raise ValueError(
783
- f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
784
- )
785
- image_embeds = added_cond_kwargs.get("image_embeds")
786
- encoder_hidden_states = self.encoder_hid_proj(image_embeds)
787
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
788
- if "image_embeds" not in added_cond_kwargs:
789
- raise ValueError(
790
- f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
791
- )
792
- image_embeds = added_cond_kwargs.get("image_embeds")
793
- image_embeds = self.encoder_hid_proj(image_embeds)
794
- encoder_hidden_states = (encoder_hidden_states, image_embeds)
795
-
796
- # 2. pre-process
797
- sample = self.conv_in(sample)
798
-
799
- # 2.5 GLIGEN position net
800
- if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
801
- cross_attention_kwargs = cross_attention_kwargs.copy()
802
- gligen_args = cross_attention_kwargs.pop("gligen")
803
- cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
804
-
805
- # 3. down
806
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
807
- if USE_PEFT_BACKEND:
808
- # weight the lora layers by setting `lora_scale` for each PEFT layer
809
- scale_lora_layers(self, lora_scale)
810
-
811
- is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
812
- # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
813
- is_adapter = down_intrablock_additional_residuals is not None
814
- # maintain backward compatibility for legacy usage, where
815
- # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
816
- # but can only use one or the other
817
- if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
818
- deprecate(
819
- "T2I should not use down_block_additional_residuals",
820
- "1.3.0",
821
- "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
822
- and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
823
- for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
824
- standard_warn=False,
825
- )
826
- down_intrablock_additional_residuals = down_block_additional_residuals
827
- is_adapter = True
828
-
829
- down_block_res_samples = (sample,)
830
- for downsample_block in self.down_blocks:
831
- if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
832
- # For t2i-adapter CrossAttnDownBlock2D
833
- additional_residuals = {}
834
- if is_adapter and len(down_intrablock_additional_residuals) > 0:
835
- additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
836
-
837
- sample, res_samples = downsample_block(
838
- hidden_states=sample,
839
- temb=emb,
840
- encoder_hidden_states=encoder_hidden_states,
841
- attention_mask=attention_mask,
842
- cross_attention_kwargs=cross_attention_kwargs,
843
- encoder_attention_mask=encoder_attention_mask,
844
- **additional_residuals,
845
- )
846
- else:
847
- sample, res_samples = downsample_block(hidden_states=sample, temb=emb, scale=lora_scale)
848
- if is_adapter and len(down_intrablock_additional_residuals) > 0:
849
- sample += down_intrablock_additional_residuals.pop(0)
850
-
851
- down_block_res_samples += res_samples
852
-
853
- if is_controlnet:
854
- new_down_block_res_samples = ()
855
-
856
- for down_block_res_sample, down_block_additional_residual in zip(
857
- down_block_res_samples, down_block_additional_residuals
858
- ):
859
- down_block_res_sample = down_block_res_sample + down_block_additional_residual
860
- new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
861
-
862
- down_block_res_samples = new_down_block_res_samples
863
-
864
- # 4. mid
865
- if self.mid_block is not None:
866
- if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
867
- sample = self.mid_block(
868
- sample,
869
- emb,
870
- encoder_hidden_states=encoder_hidden_states,
871
- attention_mask=attention_mask,
872
- cross_attention_kwargs=cross_attention_kwargs,
873
- encoder_attention_mask=encoder_attention_mask,
874
- )
875
- else:
876
- sample = self.mid_block(sample, emb)
877
-
878
- # To support T2I-Adapter-XL
879
- if (
880
- is_adapter
881
- and len(down_intrablock_additional_residuals) > 0
882
- and sample.shape == down_intrablock_additional_residuals[0].shape
883
- ):
884
- sample += down_intrablock_additional_residuals.pop(0)
885
-
886
- if is_controlnet:
887
- sample = sample + mid_block_additional_residual
888
-
889
- # 5. up
890
- for i, upsample_block in enumerate(self.up_blocks):
891
- is_final_block = i == len(self.up_blocks) - 1
892
-
893
- res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
894
- down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
895
-
896
- # if we have not reached the final block and need to forward the
897
- # upsample size, we do it here
898
- if not is_final_block and forward_upsample_size:
899
- upsample_size = down_block_res_samples[-1].shape[2:]
900
-
901
- if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
902
- sample = upsample_block(
903
- hidden_states=sample,
904
- temb=emb,
905
- res_hidden_states_tuple=res_samples,
906
- encoder_hidden_states=encoder_hidden_states,
907
- cross_attention_kwargs=cross_attention_kwargs,
908
- upsample_size=upsample_size,
909
- attention_mask=attention_mask,
910
- encoder_attention_mask=encoder_attention_mask,
911
- )
912
- else:
913
- sample = upsample_block(
914
- hidden_states=sample,
915
- temb=emb,
916
- res_hidden_states_tuple=res_samples,
917
- upsample_size=upsample_size,
918
- scale=lora_scale,
919
- )
920
-
921
- # 6. post-process
922
- if self.conv_norm_out:
923
- sample = self.conv_norm_out(sample)
924
- sample = self.conv_act(sample)
925
- sample = self.conv_out(sample)
926
-
927
- if USE_PEFT_BACKEND:
928
- # remove `lora_scale` from each PEFT layer
929
- unscale_lora_layers(self, lora_scale)
930
-
931
- if not return_dict:
932
- return (sample,)
933
-
934
- return UNet2DConditionOutput(sample=sample)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models_gpt/models/attention.py DELETED
@@ -1,668 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import Any, Dict, Optional
15
-
16
- import torch
17
- import torch.nn.functional as F
18
- from torch import nn
19
-
20
- from diffusers.utils import USE_PEFT_BACKEND
21
- from diffusers.utils.torch_utils import maybe_allow_in_graph
22
- from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
23
- from diffusers.models.attention_processor import Attention
24
- from diffusers.models.embeddings import SinusoidalPositionalEmbedding
25
- from diffusers.models.lora import LoRACompatibleLinear
26
- from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
27
-
28
-
29
- def _chunked_feed_forward(
30
- ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None
31
- ):
32
- # "feed_forward_chunk_size" can be used to save memory
33
- if hidden_states.shape[chunk_dim] % chunk_size != 0:
34
- raise ValueError(
35
- f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
36
- )
37
-
38
- num_chunks = hidden_states.shape[chunk_dim] // chunk_size
39
- if lora_scale is None:
40
- ff_output = torch.cat(
41
- [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
42
- dim=chunk_dim,
43
- )
44
- else:
45
- # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete
46
- ff_output = torch.cat(
47
- [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
48
- dim=chunk_dim,
49
- )
50
-
51
- return ff_output
52
-
53
-
54
- @maybe_allow_in_graph
55
- class GatedSelfAttentionDense(nn.Module):
56
- r"""
57
- A gated self-attention dense layer that combines visual features and object features.
58
-
59
- Parameters:
60
- query_dim (`int`): The number of channels in the query.
61
- context_dim (`int`): The number of channels in the context.
62
- n_heads (`int`): The number of heads to use for attention.
63
- d_head (`int`): The number of channels in each head.
64
- """
65
-
66
- def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
67
- super().__init__()
68
-
69
- # we need a linear projection since we need cat visual feature and obj feature
70
- self.linear = nn.Linear(context_dim, query_dim)
71
-
72
- self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
73
- self.ff = FeedForward(query_dim, activation_fn="geglu")
74
-
75
- self.norm1 = nn.LayerNorm(query_dim)
76
- self.norm2 = nn.LayerNorm(query_dim)
77
-
78
- self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
79
- self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
80
-
81
- self.enabled = True
82
-
83
- def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
84
- if not self.enabled:
85
- return x
86
-
87
- n_visual = x.shape[1]
88
- objs = self.linear(objs)
89
-
90
- x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
91
- x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
92
-
93
- return x
94
-
95
-
96
- @maybe_allow_in_graph
97
- class BasicTransformerBlock(nn.Module):
98
- r"""
99
- A basic Transformer block.
100
-
101
- Parameters:
102
- dim (`int`): The number of channels in the input and output.
103
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
104
- attention_head_dim (`int`): The number of channels in each head.
105
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
106
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
107
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
108
- num_embeds_ada_norm (:
109
- obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
110
- attention_bias (:
111
- obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
112
- only_cross_attention (`bool`, *optional*):
113
- Whether to use only cross-attention layers. In this case two cross attention layers are used.
114
- double_self_attention (`bool`, *optional*):
115
- Whether to use two self-attention layers. In this case no cross attention layers are used.
116
- upcast_attention (`bool`, *optional*):
117
- Whether to upcast the attention computation to float32. This is useful for mixed precision training.
118
- norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
119
- Whether to use learnable elementwise affine parameters for normalization.
120
- norm_type (`str`, *optional*, defaults to `"layer_norm"`):
121
- The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
122
- final_dropout (`bool` *optional*, defaults to False):
123
- Whether to apply a final dropout after the last feed-forward layer.
124
- attention_type (`str`, *optional*, defaults to `"default"`):
125
- The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
126
- positional_embeddings (`str`, *optional*, defaults to `None`):
127
- The type of positional embeddings to apply to.
128
- num_positional_embeddings (`int`, *optional*, defaults to `None`):
129
- The maximum number of positional embeddings to apply.
130
- """
131
-
132
- def __init__(
133
- self,
134
- dim: int,
135
- num_attention_heads: int,
136
- attention_head_dim: int,
137
- dropout=0.0,
138
- cross_attention_dim: Optional[int] = None,
139
- activation_fn: str = "geglu",
140
- num_embeds_ada_norm: Optional[int] = None,
141
- attention_bias: bool = False,
142
- only_cross_attention: bool = False,
143
- double_self_attention: bool = False,
144
- upcast_attention: bool = False,
145
- norm_elementwise_affine: bool = True,
146
- norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single'
147
- norm_eps: float = 1e-5,
148
- final_dropout: bool = False,
149
- attention_type: str = "default",
150
- positional_embeddings: Optional[str] = None,
151
- num_positional_embeddings: Optional[int] = None,
152
- ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
153
- ada_norm_bias: Optional[int] = None,
154
- ff_inner_dim: Optional[int] = None,
155
- ff_bias: bool = True,
156
- attention_out_bias: bool = True,
157
- ):
158
- super().__init__()
159
- self.only_cross_attention = only_cross_attention
160
-
161
- self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
162
- self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
163
- self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
164
- self.use_layer_norm = norm_type == "layer_norm"
165
- self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
166
-
167
- if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
168
- raise ValueError(
169
- f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
170
- f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
171
- )
172
-
173
- if positional_embeddings and (num_positional_embeddings is None):
174
- raise ValueError(
175
- "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
176
- )
177
-
178
- if positional_embeddings == "sinusoidal":
179
- self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
180
- else:
181
- self.pos_embed = None
182
-
183
- # Define 3 blocks. Each block has its own normalization layer.
184
- # 1. Self-Attn
185
- if self.use_ada_layer_norm:
186
- self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
187
- elif self.use_ada_layer_norm_zero:
188
- self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
189
- elif self.use_ada_layer_norm_continuous:
190
- self.norm1 = AdaLayerNormContinuous(
191
- dim,
192
- ada_norm_continous_conditioning_embedding_dim,
193
- norm_elementwise_affine,
194
- norm_eps,
195
- ada_norm_bias,
196
- "rms_norm",
197
- )
198
- else:
199
- self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
200
-
201
- self.attn1 = Attention(
202
- query_dim=dim,
203
- heads=num_attention_heads,
204
- dim_head=attention_head_dim,
205
- dropout=dropout,
206
- bias=attention_bias,
207
- cross_attention_dim=cross_attention_dim if only_cross_attention else None,
208
- upcast_attention=upcast_attention,
209
- out_bias=attention_out_bias,
210
- )
211
-
212
- # 2. Cross-Attn
213
- if cross_attention_dim is not None or double_self_attention:
214
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
215
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
216
- # the second cross attention block.
217
- if self.use_ada_layer_norm:
218
- self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
219
- elif self.use_ada_layer_norm_continuous:
220
- self.norm2 = AdaLayerNormContinuous(
221
- dim,
222
- ada_norm_continous_conditioning_embedding_dim,
223
- norm_elementwise_affine,
224
- norm_eps,
225
- ada_norm_bias,
226
- "rms_norm",
227
- )
228
- else:
229
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
230
-
231
- self.attn2 = Attention(
232
- query_dim=dim,
233
- cross_attention_dim=cross_attention_dim if not double_self_attention else None,
234
- heads=num_attention_heads,
235
- dim_head=attention_head_dim,
236
- dropout=dropout,
237
- bias=attention_bias,
238
- upcast_attention=upcast_attention,
239
- out_bias=attention_out_bias,
240
- ) # is self-attn if encoder_hidden_states is none
241
- else:
242
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
243
- self.attn2 = None
244
-
245
- # 3. Feed-forward
246
- if self.use_ada_layer_norm_continuous:
247
- self.norm3 = AdaLayerNormContinuous(
248
- dim,
249
- ada_norm_continous_conditioning_embedding_dim,
250
- norm_elementwise_affine,
251
- norm_eps,
252
- ada_norm_bias,
253
- "layer_norm",
254
- )
255
- elif not self.use_ada_layer_norm_single:
256
- self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
257
-
258
- self.ff = FeedForward(
259
- dim,
260
- dropout=dropout,
261
- activation_fn=activation_fn,
262
- final_dropout=final_dropout,
263
- inner_dim=ff_inner_dim,
264
- bias=ff_bias,
265
- )
266
-
267
- # 4. Fuser
268
- if attention_type == "gated" or attention_type == "gated-text-image":
269
- self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
270
-
271
- # 5. Scale-shift for PixArt-Alpha.
272
- if self.use_ada_layer_norm_single:
273
- self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
274
-
275
- # let chunk size default to None
276
- self._chunk_size = None
277
- self._chunk_dim = 0
278
-
279
- def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
280
- # Sets chunk feed-forward
281
- self._chunk_size = chunk_size
282
- self._chunk_dim = dim
283
-
284
- def forward(
285
- self,
286
- hidden_states: torch.FloatTensor,
287
- attention_mask: Optional[torch.FloatTensor] = None,
288
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
289
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
290
- timestep: Optional[torch.LongTensor] = None,
291
- cross_attention_kwargs: Dict[str, Any] = None,
292
- class_labels: Optional[torch.LongTensor] = None,
293
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
294
- ) -> torch.FloatTensor:
295
- # Notice that normalization is always applied before the real computation in the following blocks.
296
- # 0. Self-Attention
297
- batch_size = hidden_states.shape[0]
298
-
299
- if self.use_ada_layer_norm:
300
- norm_hidden_states = self.norm1(hidden_states, timestep)
301
- elif self.use_ada_layer_norm_zero:
302
- norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
303
- hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
304
- )
305
- elif self.use_layer_norm:
306
- norm_hidden_states = self.norm1(hidden_states)
307
- elif self.use_ada_layer_norm_continuous:
308
- norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
309
- elif self.use_ada_layer_norm_single:
310
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
311
- self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
312
- ).chunk(6, dim=1)
313
- norm_hidden_states = self.norm1(hidden_states)
314
- norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
315
- norm_hidden_states = norm_hidden_states.squeeze(1)
316
- else:
317
- raise ValueError("Incorrect norm used")
318
-
319
- if self.pos_embed is not None:
320
- norm_hidden_states = self.pos_embed(norm_hidden_states)
321
-
322
- # 1. Retrieve lora scale.
323
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
324
-
325
- # 2. Prepare GLIGEN inputs
326
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
327
- gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
328
-
329
- attn_output = self.attn1(
330
- norm_hidden_states,
331
- encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
332
- attention_mask=attention_mask,
333
- **cross_attention_kwargs,
334
- )
335
- if self.use_ada_layer_norm_zero:
336
- attn_output = gate_msa.unsqueeze(1) * attn_output
337
- elif self.use_ada_layer_norm_single:
338
- attn_output = gate_msa * attn_output
339
-
340
- hidden_states = attn_output + hidden_states
341
- if hidden_states.ndim == 4:
342
- hidden_states = hidden_states.squeeze(1)
343
-
344
- # 2.5 GLIGEN Control
345
- if gligen_kwargs is not None:
346
- hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
347
-
348
- # 3. Cross-Attention
349
- if self.attn2 is not None:
350
- if self.use_ada_layer_norm:
351
- norm_hidden_states = self.norm2(hidden_states, timestep)
352
- elif self.use_ada_layer_norm_zero or self.use_layer_norm:
353
- norm_hidden_states = self.norm2(hidden_states)
354
- elif self.use_ada_layer_norm_single:
355
- # For PixArt norm2 isn't applied here:
356
- # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
357
- norm_hidden_states = hidden_states
358
- elif self.use_ada_layer_norm_continuous:
359
- norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
360
- else:
361
- raise ValueError("Incorrect norm")
362
-
363
- if self.pos_embed is not None and self.use_ada_layer_norm_single is False:
364
- norm_hidden_states = self.pos_embed(norm_hidden_states)
365
-
366
- attn_output = self.attn2(
367
- norm_hidden_states,
368
- encoder_hidden_states=encoder_hidden_states,
369
- attention_mask=encoder_attention_mask,
370
- **cross_attention_kwargs,
371
- )
372
- hidden_states = attn_output + hidden_states
373
-
374
- # 4. Feed-forward
375
- if self.use_ada_layer_norm_continuous:
376
- norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
377
- elif not self.use_ada_layer_norm_single:
378
- norm_hidden_states = self.norm3(hidden_states)
379
-
380
- if self.use_ada_layer_norm_zero:
381
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
382
-
383
- if self.use_ada_layer_norm_single:
384
- norm_hidden_states = self.norm2(hidden_states)
385
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
386
-
387
- if self._chunk_size is not None:
388
- # "feed_forward_chunk_size" can be used to save memory
389
- ff_output = _chunked_feed_forward(
390
- self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale
391
- )
392
- else:
393
- ff_output = self.ff(norm_hidden_states, scale=lora_scale)
394
-
395
- if self.use_ada_layer_norm_zero:
396
- ff_output = gate_mlp.unsqueeze(1) * ff_output
397
- elif self.use_ada_layer_norm_single:
398
- ff_output = gate_mlp * ff_output
399
-
400
- hidden_states = ff_output + hidden_states
401
- if hidden_states.ndim == 4:
402
- hidden_states = hidden_states.squeeze(1)
403
-
404
- return hidden_states
405
-
406
-
407
- @maybe_allow_in_graph
408
- class TemporalBasicTransformerBlock(nn.Module):
409
- r"""
410
- A basic Transformer block for video like data.
411
-
412
- Parameters:
413
- dim (`int`): The number of channels in the input and output.
414
- time_mix_inner_dim (`int`): The number of channels for temporal attention.
415
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
416
- attention_head_dim (`int`): The number of channels in each head.
417
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
418
- """
419
-
420
- def __init__(
421
- self,
422
- dim: int,
423
- time_mix_inner_dim: int,
424
- num_attention_heads: int,
425
- attention_head_dim: int,
426
- cross_attention_dim: Optional[int] = None,
427
- ):
428
- super().__init__()
429
- self.is_res = dim == time_mix_inner_dim
430
-
431
- self.norm_in = nn.LayerNorm(dim)
432
-
433
- # Define 3 blocks. Each block has its own normalization layer.
434
- # 1. Self-Attn
435
- self.norm_in = nn.LayerNorm(dim)
436
- self.ff_in = FeedForward(
437
- dim,
438
- dim_out=time_mix_inner_dim,
439
- activation_fn="geglu",
440
- )
441
-
442
- self.norm1 = nn.LayerNorm(time_mix_inner_dim)
443
- self.attn1 = Attention(
444
- query_dim=time_mix_inner_dim,
445
- heads=num_attention_heads,
446
- dim_head=attention_head_dim,
447
- cross_attention_dim=None,
448
- )
449
-
450
- # 2. Cross-Attn
451
- if cross_attention_dim is not None:
452
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
453
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
454
- # the second cross attention block.
455
- self.norm2 = nn.LayerNorm(time_mix_inner_dim)
456
- self.attn2 = Attention(
457
- query_dim=time_mix_inner_dim,
458
- cross_attention_dim=cross_attention_dim,
459
- heads=num_attention_heads,
460
- dim_head=attention_head_dim,
461
- ) # is self-attn if encoder_hidden_states is none
462
- else:
463
- self.norm2 = None
464
- self.attn2 = None
465
-
466
- # 3. Feed-forward
467
- self.norm3 = nn.LayerNorm(time_mix_inner_dim)
468
- self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu")
469
-
470
- # let chunk size default to None
471
- self._chunk_size = None
472
- self._chunk_dim = None
473
-
474
- def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs):
475
- # Sets chunk feed-forward
476
- self._chunk_size = chunk_size
477
- # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off
478
- self._chunk_dim = 1
479
-
480
- def forward(
481
- self,
482
- hidden_states: torch.FloatTensor,
483
- num_frames: int,
484
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
485
- ) -> torch.FloatTensor:
486
- # Notice that normalization is always applied before the real computation in the following blocks.
487
- # 0. Self-Attention
488
- batch_size = hidden_states.shape[0]
489
-
490
- batch_frames, seq_length, channels = hidden_states.shape
491
- batch_size = batch_frames // num_frames
492
-
493
- hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels)
494
- hidden_states = hidden_states.permute(0, 2, 1, 3)
495
- hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels)
496
-
497
- residual = hidden_states
498
- hidden_states = self.norm_in(hidden_states)
499
-
500
- if self._chunk_size is not None:
501
- hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size)
502
- else:
503
- hidden_states = self.ff_in(hidden_states)
504
-
505
- if self.is_res:
506
- hidden_states = hidden_states + residual
507
-
508
- norm_hidden_states = self.norm1(hidden_states)
509
- attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None)
510
- hidden_states = attn_output + hidden_states
511
-
512
- # 3. Cross-Attention
513
- if self.attn2 is not None:
514
- norm_hidden_states = self.norm2(hidden_states)
515
- attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
516
- hidden_states = attn_output + hidden_states
517
-
518
- # 4. Feed-forward
519
- norm_hidden_states = self.norm3(hidden_states)
520
-
521
- if self._chunk_size is not None:
522
- ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
523
- else:
524
- ff_output = self.ff(norm_hidden_states)
525
-
526
- if self.is_res:
527
- hidden_states = ff_output + hidden_states
528
- else:
529
- hidden_states = ff_output
530
-
531
- hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels)
532
- hidden_states = hidden_states.permute(0, 2, 1, 3)
533
- hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels)
534
-
535
- return hidden_states
536
-
537
-
538
- class SkipFFTransformerBlock(nn.Module):
539
- def __init__(
540
- self,
541
- dim: int,
542
- num_attention_heads: int,
543
- attention_head_dim: int,
544
- kv_input_dim: int,
545
- kv_input_dim_proj_use_bias: bool,
546
- dropout=0.0,
547
- cross_attention_dim: Optional[int] = None,
548
- attention_bias: bool = False,
549
- attention_out_bias: bool = True,
550
- ):
551
- super().__init__()
552
- if kv_input_dim != dim:
553
- self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias)
554
- else:
555
- self.kv_mapper = None
556
-
557
- self.norm1 = RMSNorm(dim, 1e-06)
558
-
559
- self.attn1 = Attention(
560
- query_dim=dim,
561
- heads=num_attention_heads,
562
- dim_head=attention_head_dim,
563
- dropout=dropout,
564
- bias=attention_bias,
565
- cross_attention_dim=cross_attention_dim,
566
- out_bias=attention_out_bias,
567
- )
568
-
569
- self.norm2 = RMSNorm(dim, 1e-06)
570
-
571
- self.attn2 = Attention(
572
- query_dim=dim,
573
- cross_attention_dim=cross_attention_dim,
574
- heads=num_attention_heads,
575
- dim_head=attention_head_dim,
576
- dropout=dropout,
577
- bias=attention_bias,
578
- out_bias=attention_out_bias,
579
- )
580
-
581
- def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs):
582
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
583
-
584
- if self.kv_mapper is not None:
585
- encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states))
586
-
587
- norm_hidden_states = self.norm1(hidden_states)
588
-
589
- attn_output = self.attn1(
590
- norm_hidden_states,
591
- encoder_hidden_states=encoder_hidden_states,
592
- **cross_attention_kwargs,
593
- )
594
-
595
- hidden_states = attn_output + hidden_states
596
-
597
- norm_hidden_states = self.norm2(hidden_states)
598
-
599
- attn_output = self.attn2(
600
- norm_hidden_states,
601
- encoder_hidden_states=encoder_hidden_states,
602
- **cross_attention_kwargs,
603
- )
604
-
605
- hidden_states = attn_output + hidden_states
606
-
607
- return hidden_states
608
-
609
-
610
- class FeedForward(nn.Module):
611
- r"""
612
- A feed-forward layer.
613
-
614
- Parameters:
615
- dim (`int`): The number of channels in the input.
616
- dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
617
- mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
618
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
619
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
620
- final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
621
- bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
622
- """
623
-
624
- def __init__(
625
- self,
626
- dim: int,
627
- dim_out: Optional[int] = None,
628
- mult: int = 4,
629
- dropout: float = 0.0,
630
- activation_fn: str = "geglu",
631
- final_dropout: bool = False,
632
- inner_dim=None,
633
- bias: bool = True,
634
- ):
635
- super().__init__()
636
- if inner_dim is None:
637
- inner_dim = int(dim * mult)
638
- dim_out = dim_out if dim_out is not None else dim
639
- linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
640
-
641
- if activation_fn == "gelu":
642
- act_fn = GELU(dim, inner_dim, bias=bias)
643
- if activation_fn == "gelu-approximate":
644
- act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
645
- elif activation_fn == "geglu":
646
- act_fn = GEGLU(dim, inner_dim, bias=bias)
647
- elif activation_fn == "geglu-approximate":
648
- act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
649
-
650
- self.net = nn.ModuleList([])
651
- # project in
652
- self.net.append(act_fn)
653
- # project dropout
654
- self.net.append(nn.Dropout(dropout))
655
- # project out
656
- self.net.append(linear_cls(inner_dim, dim_out, bias=bias))
657
- # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
658
- if final_dropout:
659
- self.net.append(nn.Dropout(dropout))
660
-
661
- def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
662
- compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear)
663
- for module in self.net:
664
- if isinstance(module, compatible_cls):
665
- hidden_states = module(hidden_states, scale)
666
- else:
667
- hidden_states = module(hidden_states)
668
- return hidden_states
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models_gpt/models/attention_add_rot_emb.py DELETED
@@ -1,724 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import Any, Dict, Optional
15
-
16
- import torch
17
- import torch.nn.functional as F
18
- from torch import nn
19
-
20
- from diffusers.utils import USE_PEFT_BACKEND
21
- from diffusers.utils.torch_utils import maybe_allow_in_graph
22
- from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
23
- from diffusers.models.attention_processor import Attention
24
- from diffusers.models.embeddings import SinusoidalPositionalEmbedding
25
- from diffusers.models.lora import LoRACompatibleLinear
26
- from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
27
-
28
-
29
- def _chunked_feed_forward(
30
- ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None
31
- ):
32
- # "feed_forward_chunk_size" can be used to save memory
33
- if hidden_states.shape[chunk_dim] % chunk_size != 0:
34
- raise ValueError(
35
- f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
36
- )
37
-
38
- num_chunks = hidden_states.shape[chunk_dim] // chunk_size
39
- if lora_scale is None:
40
- ff_output = torch.cat(
41
- [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
42
- dim=chunk_dim,
43
- )
44
- else:
45
- # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete
46
- ff_output = torch.cat(
47
- [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
48
- dim=chunk_dim,
49
- )
50
-
51
- return ff_output
52
-
53
-
54
- @maybe_allow_in_graph
55
- class GatedSelfAttentionDense(nn.Module):
56
- r"""
57
- A gated self-attention dense layer that combines visual features and object features.
58
-
59
- Parameters:
60
- query_dim (`int`): The number of channels in the query.
61
- context_dim (`int`): The number of channels in the context.
62
- n_heads (`int`): The number of heads to use for attention.
63
- d_head (`int`): The number of channels in each head.
64
- """
65
-
66
- def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
67
- super().__init__()
68
-
69
- # we need a linear projection since we need cat visual feature and obj feature
70
- self.linear = nn.Linear(context_dim, query_dim)
71
-
72
- self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
73
- self.ff = FeedForward(query_dim, activation_fn="geglu")
74
-
75
- self.norm1 = nn.LayerNorm(query_dim)
76
- self.norm2 = nn.LayerNorm(query_dim)
77
-
78
- self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
79
- self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
80
-
81
- self.enabled = True
82
-
83
- def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
84
- if not self.enabled:
85
- return x
86
-
87
- n_visual = x.shape[1]
88
- objs = self.linear(objs)
89
-
90
- x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
91
- x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
92
-
93
- return x
94
- def precompute_freqs_cis(dim: int, seq_len: int, theta: float = 10000.0):
95
- # 计算词向量元素两两分组之后,每组元素对应的旋转角度
96
- freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
97
- # 生成 token 序列索引 t = [0, 1,..., seq_len-1]
98
- t = torch.arange(seq_len, device=freqs.device)
99
- # freqs.shape = [seq_len, dim // 2]
100
- freqs = torch.outer(t, freqs).float()
101
- # torch.polar 的文档
102
- # https://pytorch.org/docs/stable/generated/torch.polar.html
103
- # 计算结果是个复数向量
104
- # 假设 freqs = [x, y]
105
- # 则 freqs_cis = [cos(x) + sin(x)i, cos(y) + sin(y)i]
106
- freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
107
- return freqs_cis
108
-
109
- def apply_rotary_emb(
110
- xq: torch.Tensor,
111
- freqs_cis: torch.Tensor,
112
- ):
113
- # xq.shape = [batch_size, seq_len, dim]
114
- # xq_.shape = [batch_size, seq_len, dim // 2, 2]
115
- xq_ = xq.float().reshape(*xq.shape[:-1], -1, 2).to(freqs_cis.device)
116
-
117
- # 转为复数域
118
- xq_ = torch.view_as_complex(xq_)
119
-
120
- # 应用旋转操作,然后将结果转回实数域
121
- # xq_out.shape = [batch_size, seq_len, dim]
122
- xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(2)
123
- return xq_out.type_as(xq)
124
-
125
-
126
-
127
- @maybe_allow_in_graph
128
- class BasicTransformerBlock(nn.Module):
129
- r"""
130
- A basic Transformer block.
131
-
132
- Parameters:
133
- dim (`int`): The number of channels in the input and output.
134
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
135
- attention_head_dim (`int`): The number of channels in each head.
136
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
137
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
138
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
139
- num_embeds_ada_norm (:
140
- obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
141
- attention_bias (:
142
- obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
143
- only_cross_attention (`bool`, *optional*):
144
- Whether to use only cross-attention layers. In this case two cross attention layers are used.
145
- double_self_attention (`bool`, *optional*):
146
- Whether to use two self-attention layers. In this case no cross attention layers are used.
147
- upcast_attention (`bool`, *optional*):
148
- Whether to upcast the attention computation to float32. This is useful for mixed precision training.
149
- norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
150
- Whether to use learnable elementwise affine parameters for normalization.
151
- norm_type (`str`, *optional*, defaults to `"layer_norm"`):
152
- The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
153
- final_dropout (`bool` *optional*, defaults to False):
154
- Whether to apply a final dropout after the last feed-forward layer.
155
- attention_type (`str`, *optional*, defaults to `"default"`):
156
- The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
157
- positional_embeddings (`str`, *optional*, defaults to `None`):
158
- The type of positional embeddings to apply to.
159
- num_positional_embeddings (`int`, *optional*, defaults to `None`):
160
- The maximum number of positional embeddings to apply.
161
- """
162
-
163
- def __init__(
164
- self,
165
- dim: int,
166
- num_attention_heads: int,
167
- attention_head_dim: int,
168
- dropout=0.0,
169
- cross_attention_dim: Optional[int] = None,
170
- activation_fn: str = "geglu",
171
- num_embeds_ada_norm: Optional[int] = None,
172
- attention_bias: bool = False,
173
- only_cross_attention: bool = False,
174
- double_self_attention: bool = False,
175
- upcast_attention: bool = False,
176
- norm_elementwise_affine: bool = True,
177
- norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single'
178
- norm_eps: float = 1e-5,
179
- final_dropout: bool = False,
180
- attention_type: str = "default",
181
- positional_embeddings: Optional[str] = None,
182
- num_positional_embeddings: Optional[int] = None,
183
- ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
184
- ada_norm_bias: Optional[int] = None,
185
- ff_inner_dim: Optional[int] = None,
186
- ff_bias: bool = True,
187
- attention_out_bias: bool = True,
188
- ):
189
- super().__init__()
190
- self.only_cross_attention = only_cross_attention
191
-
192
- self.freqs_cis = precompute_freqs_cis(dim, 2000)
193
-
194
- self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
195
- self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
196
- self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
197
- self.use_layer_norm = norm_type == "layer_norm"
198
- self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
199
-
200
- if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
201
- raise ValueError(
202
- f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
203
- f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
204
- )
205
-
206
- if positional_embeddings and (num_positional_embeddings is None):
207
- raise ValueError(
208
- "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
209
- )
210
-
211
- if positional_embeddings == "sinusoidal":
212
- self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
213
- else:
214
- self.pos_embed = None
215
-
216
- # Define 3 blocks. Each block has its own normalization layer.
217
- # 1. Self-Attn
218
- if self.use_ada_layer_norm:
219
- self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
220
- elif self.use_ada_layer_norm_zero:
221
- self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
222
- elif self.use_ada_layer_norm_continuous:
223
- self.norm1 = AdaLayerNormContinuous(
224
- dim,
225
- ada_norm_continous_conditioning_embedding_dim,
226
- norm_elementwise_affine,
227
- norm_eps,
228
- ada_norm_bias,
229
- "rms_norm",
230
- )
231
- else:
232
- self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
233
-
234
- self.attn1 = Attention(
235
- query_dim=dim,
236
- heads=num_attention_heads,
237
- dim_head=attention_head_dim,
238
- dropout=dropout,
239
- bias=attention_bias,
240
- cross_attention_dim=cross_attention_dim if only_cross_attention else None,
241
- upcast_attention=upcast_attention,
242
- out_bias=attention_out_bias,
243
- )
244
-
245
- # 2. Cross-Attn
246
- if cross_attention_dim is not None or double_self_attention:
247
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
248
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
249
- # the second cross attention block.
250
- if self.use_ada_layer_norm:
251
- self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
252
- elif self.use_ada_layer_norm_continuous:
253
- self.norm2 = AdaLayerNormContinuous(
254
- dim,
255
- ada_norm_continous_conditioning_embedding_dim,
256
- norm_elementwise_affine,
257
- norm_eps,
258
- ada_norm_bias,
259
- "rms_norm",
260
- )
261
- else:
262
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
263
-
264
- self.attn2 = Attention(
265
- query_dim=dim,
266
- cross_attention_dim=cross_attention_dim if not double_self_attention else None,
267
- heads=num_attention_heads,
268
- dim_head=attention_head_dim,
269
- dropout=dropout,
270
- bias=attention_bias,
271
- upcast_attention=upcast_attention,
272
- out_bias=attention_out_bias,
273
- ) # is self-attn if encoder_hidden_states is none
274
- else:
275
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
276
- self.attn2 = None
277
-
278
- # 3. Feed-forward
279
- if self.use_ada_layer_norm_continuous:
280
- self.norm3 = AdaLayerNormContinuous(
281
- dim,
282
- ada_norm_continous_conditioning_embedding_dim,
283
- norm_elementwise_affine,
284
- norm_eps,
285
- ada_norm_bias,
286
- "layer_norm",
287
- )
288
- elif not self.use_ada_layer_norm_single:
289
- self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
290
-
291
- self.ff = FeedForward(
292
- dim,
293
- dropout=dropout,
294
- activation_fn=activation_fn,
295
- final_dropout=final_dropout,
296
- inner_dim=ff_inner_dim,
297
- bias=ff_bias,
298
- )
299
-
300
- # 4. Fuser
301
- if attention_type == "gated" or attention_type == "gated-text-image":
302
- self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
303
-
304
- # 5. Scale-shift for PixArt-Alpha.
305
- if self.use_ada_layer_norm_single:
306
- self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
307
-
308
- # let chunk size default to None
309
- self._chunk_size = None
310
- self._chunk_dim = 0
311
-
312
- def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
313
- # Sets chunk feed-forward
314
- self._chunk_size = chunk_size
315
- self._chunk_dim = dim
316
-
317
- def forward(
318
- self,
319
- hidden_states: torch.FloatTensor,
320
- attention_mask: Optional[torch.FloatTensor] = None,
321
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
322
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
323
- timestep: Optional[torch.LongTensor] = None,
324
- cross_attention_kwargs: Dict[str, Any] = None,
325
- class_labels: Optional[torch.LongTensor] = None,
326
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
327
- ) -> torch.FloatTensor:
328
- # Notice that normalization is always applied before the real computation in the following blocks.
329
- # 0. Self-Attention
330
- batch_size = hidden_states.shape[0]
331
-
332
- if self.use_ada_layer_norm:
333
- norm_hidden_states = self.norm1(hidden_states, timestep)
334
- elif self.use_ada_layer_norm_zero:
335
- norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
336
- hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
337
- )
338
- elif self.use_layer_norm:
339
- norm_hidden_states = self.norm1(hidden_states)
340
- elif self.use_ada_layer_norm_continuous:
341
- norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
342
- elif self.use_ada_layer_norm_single:
343
- # print("Using PixArt-Alpha norm")
344
- # print("time step: ", timestep.shape)
345
- # print("self.scale_shift_table: ", self.scale_shift_table.shape)
346
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
347
- self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
348
- ).chunk(6, dim=1)
349
- norm_hidden_states = self.norm1(hidden_states)
350
- # print("scale_msa: ", scale_msa.shape)
351
- # print("shift_msa: ", shift_msa.shape)
352
- #scale_msa: torch.Size([5, 1, 1152])
353
- #shift_msa: torch.Size([5, 1, 1152])
354
- # exit()
355
- # print("before: ", norm_hidden_states.shape)
356
- #before: torch.Size([5, 3584, 1152])
357
- norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
358
- # print("after: ", norm_hidden_states.shape)
359
- #before: torch.Size([5, 3584, 1152])
360
- # exit()
361
- norm_hidden_states = norm_hidden_states.squeeze(1)
362
- else:
363
- raise ValueError("Incorrect norm used")
364
-
365
- if self.pos_embed is not None:
366
- norm_hidden_states = self.pos_embed(norm_hidden_states)
367
-
368
- # print("norm_hidden_states1: ", norm_hidden_states.shape)
369
- norm_hidden_states = apply_rotary_emb(norm_hidden_states, self.freqs_cis)
370
- # print("norm_hidden_states2: ", norm_hidden_states.shape)
371
-
372
- # 1. Retrieve lora scale.
373
- lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
374
-
375
- # 2. Prepare GLIGEN inputs
376
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
377
- gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
378
-
379
- attn_output = self.attn1(
380
- norm_hidden_states,
381
- encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
382
- attention_mask=attention_mask,
383
- **cross_attention_kwargs,
384
- )
385
- if self.use_ada_layer_norm_zero:
386
- attn_output = gate_msa.unsqueeze(1) * attn_output
387
- elif self.use_ada_layer_norm_single:
388
- attn_output = gate_msa * attn_output
389
-
390
- hidden_states = attn_output + hidden_states
391
- if hidden_states.ndim == 4:
392
- hidden_states = hidden_states.squeeze(1)
393
-
394
- # 2.5 GLIGEN Control
395
- if gligen_kwargs is not None:
396
- hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
397
-
398
- # 3. Cross-Attention
399
- if self.attn2 is not None:
400
- if self.use_ada_layer_norm:
401
- norm_hidden_states = self.norm2(hidden_states, timestep)
402
- elif self.use_ada_layer_norm_zero or self.use_layer_norm:
403
- norm_hidden_states = self.norm2(hidden_states)
404
- elif self.use_ada_layer_norm_single:
405
- # For PixArt norm2 isn't applied here:
406
- # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
407
- norm_hidden_states = hidden_states
408
- elif self.use_ada_layer_norm_continuous:
409
- norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
410
- else:
411
- raise ValueError("Incorrect norm")
412
-
413
- if self.pos_embed is not None and self.use_ada_layer_norm_single is False:
414
- norm_hidden_states = self.pos_embed(norm_hidden_states)
415
- # print("1")
416
- # print("norm_hidden_states:",norm_hidden_states.shape)
417
- norm_hidden_states = apply_rotary_emb(norm_hidden_states, self.freqs_cis)
418
- # print("norm_hidden_states:",norm_hidden_states.shape)
419
-
420
- attn_output = self.attn2(
421
- norm_hidden_states,
422
- encoder_hidden_states=encoder_hidden_states,
423
- attention_mask=encoder_attention_mask,
424
- **cross_attention_kwargs,
425
- )
426
- # print("attn_output: ", attn_output.shape)
427
- # print("hidden_states: ", hidden_states.shape)
428
- hidden_states = attn_output + hidden_states
429
-
430
- # 4. Feed-forward
431
- if self.use_ada_layer_norm_continuous:
432
- norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
433
- elif not self.use_ada_layer_norm_single:
434
- norm_hidden_states = self.norm3(hidden_states)
435
-
436
- if self.use_ada_layer_norm_zero:
437
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
438
-
439
- if self.use_ada_layer_norm_single:
440
- norm_hidden_states = self.norm2(hidden_states)
441
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
442
-
443
- if self._chunk_size is not None:
444
- # "feed_forward_chunk_size" can be used to save memory
445
- ff_output = _chunked_feed_forward(
446
- self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale
447
- )
448
- else:
449
- ff_output = self.ff(norm_hidden_states, scale=lora_scale)
450
-
451
- if self.use_ada_layer_norm_zero:
452
- ff_output = gate_mlp.unsqueeze(1) * ff_output
453
- elif self.use_ada_layer_norm_single:
454
- ff_output = gate_mlp * ff_output
455
-
456
- hidden_states = ff_output + hidden_states
457
- if hidden_states.ndim == 4:
458
- hidden_states = hidden_states.squeeze(1)
459
-
460
- return hidden_states
461
-
462
-
463
- @maybe_allow_in_graph
464
- class TemporalBasicTransformerBlock(nn.Module):
465
- r"""
466
- A basic Transformer block for video like data.
467
-
468
- Parameters:
469
- dim (`int`): The number of channels in the input and output.
470
- time_mix_inner_dim (`int`): The number of channels for temporal attention.
471
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
472
- attention_head_dim (`int`): The number of channels in each head.
473
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
474
- """
475
-
476
- def __init__(
477
- self,
478
- dim: int,
479
- time_mix_inner_dim: int,
480
- num_attention_heads: int,
481
- attention_head_dim: int,
482
- cross_attention_dim: Optional[int] = None,
483
- ):
484
- super().__init__()
485
- self.is_res = dim == time_mix_inner_dim
486
-
487
- self.norm_in = nn.LayerNorm(dim)
488
-
489
- # Define 3 blocks. Each block has its own normalization layer.
490
- # 1. Self-Attn
491
- self.norm_in = nn.LayerNorm(dim)
492
- self.ff_in = FeedForward(
493
- dim,
494
- dim_out=time_mix_inner_dim,
495
- activation_fn="geglu",
496
- )
497
-
498
- self.norm1 = nn.LayerNorm(time_mix_inner_dim)
499
- self.attn1 = Attention(
500
- query_dim=time_mix_inner_dim,
501
- heads=num_attention_heads,
502
- dim_head=attention_head_dim,
503
- cross_attention_dim=None,
504
- )
505
-
506
- # 2. Cross-Attn
507
- if cross_attention_dim is not None:
508
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
509
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
510
- # the second cross attention block.
511
- self.norm2 = nn.LayerNorm(time_mix_inner_dim)
512
- self.attn2 = Attention(
513
- query_dim=time_mix_inner_dim,
514
- cross_attention_dim=cross_attention_dim,
515
- heads=num_attention_heads,
516
- dim_head=attention_head_dim,
517
- ) # is self-attn if encoder_hidden_states is none
518
- else:
519
- self.norm2 = None
520
- self.attn2 = None
521
-
522
- # 3. Feed-forward
523
- self.norm3 = nn.LayerNorm(time_mix_inner_dim)
524
- self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu")
525
-
526
- # let chunk size default to None
527
- self._chunk_size = None
528
- self._chunk_dim = None
529
-
530
- def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs):
531
- # Sets chunk feed-forward
532
- self._chunk_size = chunk_size
533
- # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off
534
- self._chunk_dim = 1
535
-
536
- def forward(
537
- self,
538
- hidden_states: torch.FloatTensor,
539
- num_frames: int,
540
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
541
- ) -> torch.FloatTensor:
542
- # Notice that normalization is always applied before the real computation in the following blocks.
543
- # 0. Self-Attention
544
- batch_size = hidden_states.shape[0]
545
-
546
- batch_frames, seq_length, channels = hidden_states.shape
547
- batch_size = batch_frames // num_frames
548
-
549
- hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels)
550
- hidden_states = hidden_states.permute(0, 2, 1, 3)
551
- hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels)
552
-
553
- residual = hidden_states
554
- hidden_states = self.norm_in(hidden_states)
555
-
556
- if self._chunk_size is not None:
557
- hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size)
558
- else:
559
- hidden_states = self.ff_in(hidden_states)
560
-
561
- if self.is_res:
562
- hidden_states = hidden_states + residual
563
-
564
- norm_hidden_states = self.norm1(hidden_states)
565
- attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None)
566
- hidden_states = attn_output + hidden_states
567
-
568
- # 3. Cross-Attention
569
- if self.attn2 is not None:
570
- norm_hidden_states = self.norm2(hidden_states)
571
- attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
572
- hidden_states = attn_output + hidden_states
573
-
574
- # 4. Feed-forward
575
- norm_hidden_states = self.norm3(hidden_states)
576
-
577
- if self._chunk_size is not None:
578
- ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
579
- else:
580
- ff_output = self.ff(norm_hidden_states)
581
-
582
- if self.is_res:
583
- hidden_states = ff_output + hidden_states
584
- else:
585
- hidden_states = ff_output
586
-
587
- hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels)
588
- hidden_states = hidden_states.permute(0, 2, 1, 3)
589
- hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels)
590
-
591
- return hidden_states
592
-
593
-
594
- class SkipFFTransformerBlock(nn.Module):
595
- def __init__(
596
- self,
597
- dim: int,
598
- num_attention_heads: int,
599
- attention_head_dim: int,
600
- kv_input_dim: int,
601
- kv_input_dim_proj_use_bias: bool,
602
- dropout=0.0,
603
- cross_attention_dim: Optional[int] = None,
604
- attention_bias: bool = False,
605
- attention_out_bias: bool = True,
606
- ):
607
- super().__init__()
608
- if kv_input_dim != dim:
609
- self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias)
610
- else:
611
- self.kv_mapper = None
612
-
613
- self.norm1 = RMSNorm(dim, 1e-06)
614
-
615
- self.attn1 = Attention(
616
- query_dim=dim,
617
- heads=num_attention_heads,
618
- dim_head=attention_head_dim,
619
- dropout=dropout,
620
- bias=attention_bias,
621
- cross_attention_dim=cross_attention_dim,
622
- out_bias=attention_out_bias,
623
- )
624
-
625
- self.norm2 = RMSNorm(dim, 1e-06)
626
-
627
- self.attn2 = Attention(
628
- query_dim=dim,
629
- cross_attention_dim=cross_attention_dim,
630
- heads=num_attention_heads,
631
- dim_head=attention_head_dim,
632
- dropout=dropout,
633
- bias=attention_bias,
634
- out_bias=attention_out_bias,
635
- )
636
-
637
- def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs):
638
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
639
-
640
- if self.kv_mapper is not None:
641
- encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states))
642
-
643
- norm_hidden_states = self.norm1(hidden_states)
644
-
645
- attn_output = self.attn1(
646
- norm_hidden_states,
647
- encoder_hidden_states=encoder_hidden_states,
648
- **cross_attention_kwargs,
649
- )
650
-
651
- hidden_states = attn_output + hidden_states
652
-
653
- norm_hidden_states = self.norm2(hidden_states)
654
-
655
- attn_output = self.attn2(
656
- norm_hidden_states,
657
- encoder_hidden_states=encoder_hidden_states,
658
- **cross_attention_kwargs,
659
- )
660
-
661
- hidden_states = attn_output + hidden_states
662
-
663
- return hidden_states
664
-
665
-
666
- class FeedForward(nn.Module):
667
- r"""
668
- A feed-forward layer.
669
-
670
- Parameters:
671
- dim (`int`): The number of channels in the input.
672
- dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
673
- mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
674
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
675
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
676
- final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
677
- bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
678
- """
679
-
680
- def __init__(
681
- self,
682
- dim: int,
683
- dim_out: Optional[int] = None,
684
- mult: int = 4,
685
- dropout: float = 0.0,
686
- activation_fn: str = "geglu",
687
- final_dropout: bool = False,
688
- inner_dim=None,
689
- bias: bool = True,
690
- ):
691
- super().__init__()
692
- if inner_dim is None:
693
- inner_dim = int(dim * mult)
694
- dim_out = dim_out if dim_out is not None else dim
695
- linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
696
-
697
- if activation_fn == "gelu":
698
- act_fn = GELU(dim, inner_dim, bias=bias)
699
- if activation_fn == "gelu-approximate":
700
- act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
701
- elif activation_fn == "geglu":
702
- act_fn = GEGLU(dim, inner_dim, bias=bias)
703
- elif activation_fn == "geglu-approximate":
704
- act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
705
-
706
- self.net = nn.ModuleList([])
707
- # project in
708
- self.net.append(act_fn)
709
- # project dropout
710
- self.net.append(nn.Dropout(dropout))
711
- # project out
712
- self.net.append(linear_cls(inner_dim, dim_out, bias=bias))
713
- # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
714
- if final_dropout:
715
- self.net.append(nn.Dropout(dropout))
716
-
717
- def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
718
- compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear)
719
- for module in self.net:
720
- if isinstance(module, compatible_cls):
721
- hidden_states = module(hidden_states, scale)
722
- else:
723
- hidden_states = module(hidden_states)
724
- return hidden_states
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codeclm/tokenizer/Flow1dVAE/models_gpt/models/gpt2.py DELETED
@@ -1,1954 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
3
- # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
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 OpenAI GPT-2 model."""
17
-
18
- import math
19
- import os
20
- import warnings
21
- from dataclasses import dataclass
22
- from typing import Optional, Tuple, Union
23
-
24
- import torch
25
- import torch.nn.functional as F
26
- import torch.utils.checkpoint
27
- from torch import nn
28
- from torch.cuda.amp import autocast
29
- from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
-
31
- from transformers.activations import ACT2FN
32
- from transformers.modeling_outputs import (
33
- BaseModelOutputWithPastAndCrossAttentions,
34
- CausalLMOutputWithCrossAttentions,
35
- QuestionAnsweringModelOutput,
36
- SequenceClassifierOutputWithPast,
37
- TokenClassifierOutput,
38
- )
39
- from transformers.modeling_utils import PreTrainedModel, SequenceSummary
40
- from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
41
- from transformers.utils import (
42
- ModelOutput,
43
- add_code_sample_docstrings,
44
- add_start_docstrings,
45
- add_start_docstrings_to_model_forward,
46
- is_flash_attn_2_available,
47
- is_flash_attn_greater_or_equal_2_10,
48
- logging,
49
- replace_return_docstrings,
50
- )
51
- from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
52
- from models.gpt2_config import GPT2Config
53
-
54
-
55
- if is_flash_attn_2_available():
56
- from flash_attn import flash_attn_func, flash_attn_varlen_func
57
- from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
58
-
59
-
60
- logger = logging.get_logger(__name__)
61
-
62
- _CHECKPOINT_FOR_DOC = "openai-community/gpt2"
63
- _CONFIG_FOR_DOC = "GPT2Config"
64
-
65
-
66
- # Copied from transformers.models.llama.modeling_llama._get_unpad_data
67
- def _get_unpad_data(attention_mask):
68
- seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
69
- indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
70
- max_seqlen_in_batch = seqlens_in_batch.max().item()
71
- cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
72
- return (
73
- indices,
74
- cu_seqlens,
75
- max_seqlen_in_batch,
76
- )
77
-
78
-
79
- def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
80
- """Load tf checkpoints in a pytorch model"""
81
- try:
82
- import re
83
-
84
- import tensorflow as tf
85
- except ImportError:
86
- logger.error(
87
- "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
88
- "https://www.tensorflow.org/install/ for installation instructions."
89
- )
90
- raise
91
- tf_path = os.path.abspath(gpt2_checkpoint_path)
92
- logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
93
- # Load weights from TF model
94
- init_vars = tf.train.list_variables(tf_path)
95
- names = []
96
- arrays = []
97
- for name, shape in init_vars:
98
- logger.info(f"Loading TF weight {name} with shape {shape}")
99
- array = tf.train.load_variable(tf_path, name)
100
- names.append(name)
101
- arrays.append(array.squeeze())
102
-
103
- for name, array in zip(names, arrays):
104
- name = name[6:] # skip "model/"
105
- name = name.split("/")
106
- pointer = model
107
- for m_name in name:
108
- if re.fullmatch(r"[A-Za-z]+\d+", m_name):
109
- scope_names = re.split(r"(\d+)", m_name)
110
- else:
111
- scope_names = [m_name]
112
- if scope_names[0] == "w" or scope_names[0] == "g":
113
- pointer = getattr(pointer, "weight")
114
- elif scope_names[0] == "b":
115
- pointer = getattr(pointer, "bias")
116
- elif scope_names[0] == "wpe" or scope_names[0] == "wte":
117
- pointer = getattr(pointer, scope_names[0])
118
- pointer = getattr(pointer, "weight")
119
- else:
120
- pointer = getattr(pointer, scope_names[0])
121
- if len(scope_names) >= 2:
122
- num = int(scope_names[1])
123
- pointer = pointer[num]
124
- try:
125
- if pointer.shape != array.shape:
126
- raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
127
- except ValueError as e:
128
- e.args += (pointer.shape, array.shape)
129
- raise
130
- logger.info(f"Initialize PyTorch weight {name}")
131
- pointer.data = torch.from_numpy(array)
132
- return model
133
-
134
-
135
- class GPT2Attention(nn.Module):
136
- def __init__(self, config, is_cross_attention=False, layer_idx=None):
137
- super().__init__()
138
- self.config = config
139
- max_positions = config.max_position_embeddings
140
- self.register_buffer(
141
- "bias",
142
- torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
143
- 1, 1, max_positions, max_positions
144
- ),
145
- persistent=False,
146
- )
147
- self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
148
-
149
- self.embed_dim = config.hidden_size
150
- self.num_heads = config.num_attention_heads
151
- self.head_dim = self.embed_dim // self.num_heads
152
- self.split_size = self.embed_dim
153
- if self.head_dim * self.num_heads != self.embed_dim:
154
- raise ValueError(
155
- f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
156
- f" {self.num_heads})."
157
- )
158
-
159
- self.scale_attn_weights = config.scale_attn_weights
160
- self.is_cross_attention = is_cross_attention
161
-
162
- # Layer-wise attention scaling, reordering, and upcasting
163
- self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
164
- self.layer_idx = layer_idx
165
- self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
166
-
167
- if self.is_cross_attention:
168
- self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
169
- self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
170
- else:
171
- self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
172
- self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
173
-
174
- self.attn_dropout = nn.Dropout(config.attn_pdrop)
175
- self.resid_dropout = nn.Dropout(config.resid_pdrop)
176
- self.is_causal = True
177
-
178
- self.pruned_heads = set()
179
-
180
- def prune_heads(self, heads):
181
- if len(heads) == 0:
182
- return
183
- heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
184
- index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
185
-
186
- # Prune conv1d layers
187
- self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
188
- self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
189
-
190
- # Update hyper params
191
- self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
192
- self.num_heads = self.num_heads - len(heads)
193
- self.pruned_heads = self.pruned_heads.union(heads)
194
-
195
- def _attn(self, query, key, value, attention_mask=None, head_mask=None):
196
- attn_weights = torch.matmul(query, key.transpose(-1, -2))
197
-
198
- if self.scale_attn_weights:
199
- attn_weights = attn_weights / torch.full(
200
- [], value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
201
- )
202
-
203
- # Layer-wise attention scaling
204
- if self.scale_attn_by_inverse_layer_idx:
205
- attn_weights = attn_weights / float(self.layer_idx + 1)
206
-
207
- if not self.is_cross_attention:
208
- # if only "normal" attention layer implements causal mask
209
- query_length, key_length = query.size(-2), key.size(-2)
210
- causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
211
- mask_value = torch.finfo(attn_weights.dtype).min
212
- # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
213
- # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
214
- mask_value = torch.full([], mask_value, dtype=attn_weights.dtype, device=attn_weights.device)
215
- attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
216
-
217
- if attention_mask is not None:
218
- # Apply the attention mask
219
- attn_weights = attn_weights + attention_mask
220
-
221
- attn_weights = nn.functional.softmax(attn_weights, dim=-1)
222
-
223
- # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
224
- attn_weights = attn_weights.type(value.dtype)
225
- attn_weights = self.attn_dropout(attn_weights)
226
-
227
- # Mask heads if we want to
228
- if head_mask is not None:
229
- attn_weights = attn_weights * head_mask
230
-
231
- attn_output = torch.matmul(attn_weights, value)
232
-
233
- return attn_output, attn_weights
234
-
235
- def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None):
236
- # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
237
- bsz, num_heads, q_seq_len, dk = query.size()
238
- _, _, k_seq_len, _ = key.size()
239
-
240
- # Preallocate attn_weights for `baddbmm`
241
- attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
242
-
243
- # Compute Scale Factor
244
- scale_factor = 1.0
245
- if self.scale_attn_weights:
246
- scale_factor /= float(value.size(-1)) ** 0.5
247
-
248
- if self.scale_attn_by_inverse_layer_idx:
249
- scale_factor /= float(self.layer_idx + 1)
250
-
251
- # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
252
- with autocast(enabled=False):
253
- q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
254
- attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
255
- attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
256
-
257
- if not self.is_cross_attention:
258
- # if only "normal" attention layer implements causal mask
259
- query_length, key_length = query.size(-2), key.size(-2)
260
- causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
261
- mask_value = torch.finfo(attn_weights.dtype).min
262
- # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
263
- # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
264
- mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
265
- attn_weights = torch.where(causal_mask, attn_weights, mask_value)
266
-
267
- if attention_mask is not None:
268
- # Apply the attention mask
269
- attn_weights = attn_weights + attention_mask
270
-
271
- attn_weights = nn.functional.softmax(attn_weights, dim=-1)
272
-
273
- # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
274
- if attn_weights.dtype != torch.float32:
275
- raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
276
- attn_weights = attn_weights.type(value.dtype)
277
- attn_weights = self.attn_dropout(attn_weights)
278
-
279
- # Mask heads if we want to
280
- if head_mask is not None:
281
- attn_weights = attn_weights * head_mask
282
-
283
- attn_output = torch.matmul(attn_weights, value)
284
-
285
- return attn_output, attn_weights
286
-
287
- def _split_heads(self, tensor, num_heads, attn_head_size):
288
- """
289
- Splits hidden_size dim into attn_head_size and num_heads
290
- """
291
- new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
292
- tensor = tensor.view(new_shape)
293
- return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
294
-
295
- def _merge_heads(self, tensor, num_heads, attn_head_size):
296
- """
297
- Merges attn_head_size dim and num_attn_heads dim into hidden_size
298
- """
299
- tensor = tensor.permute(0, 2, 1, 3).contiguous()
300
- new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
301
- return tensor.view(new_shape)
302
-
303
- def forward(
304
- self,
305
- hidden_states: Optional[Tuple[torch.FloatTensor]],
306
- layer_past: Optional[Tuple[torch.Tensor]] = None,
307
- attention_mask: Optional[torch.FloatTensor] = None,
308
- head_mask: Optional[torch.FloatTensor] = None,
309
- encoder_hidden_states: Optional[torch.Tensor] = None,
310
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
311
- use_cache: Optional[bool] = False,
312
- output_attentions: Optional[bool] = False,
313
- ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
314
- if encoder_hidden_states is not None:
315
- if not hasattr(self, "q_attn"):
316
- raise ValueError(
317
- "If class is used as cross attention, the weights `q_attn` have to be defined. "
318
- "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
319
- )
320
-
321
- query = self.q_attn(hidden_states)
322
- key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
323
- attention_mask = encoder_attention_mask
324
- else:
325
- query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
326
-
327
- query = self._split_heads(query, self.num_heads, self.head_dim)
328
- key = self._split_heads(key, self.num_heads, self.head_dim)
329
- value = self._split_heads(value, self.num_heads, self.head_dim)
330
-
331
- if layer_past is not None:
332
- past_key, past_value = layer_past
333
- key = torch.cat((past_key, key), dim=-2)
334
- value = torch.cat((past_value, value), dim=-2)
335
-
336
- if use_cache is True:
337
- present = (key, value)
338
- else:
339
- present = None
340
-
341
- if self.reorder_and_upcast_attn:
342
- attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask, head_mask)
343
- else:
344
- attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
345
-
346
- attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
347
- attn_output = self.c_proj(attn_output)
348
- attn_output = self.resid_dropout(attn_output)
349
-
350
- outputs = (attn_output, present)
351
- if output_attentions:
352
- outputs += (attn_weights,)
353
-
354
- return outputs # a, present, (attentions)
355
-
356
-
357
-
358
-
359
-
360
-
361
- class GPT2FlashAttention2(GPT2Attention):
362
- """
363
- GPT2 flash attention module. This module inherits from `GPT2Attention` as the weights of the module stays
364
- untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
365
- flash attention and deal with padding tokens in case the input contains any of them.
366
- """
367
-
368
- def __init__(self, *args, **kwargs):
369
- super().__init__(*args, **kwargs)
370
-
371
- # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
372
- # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
373
- # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
374
- self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
375
-
376
- def forward(
377
- self,
378
- hidden_states: Optional[Tuple[torch.FloatTensor]],
379
- layer_past: Optional[Tuple[torch.Tensor]] = None,
380
- attention_mask: Optional[torch.FloatTensor] = None,
381
- head_mask: Optional[torch.FloatTensor] = None,
382
- encoder_hidden_states: Optional[torch.Tensor] = None,
383
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
384
- use_cache: Optional[bool] = False,
385
- output_attentions: Optional[bool] = False,
386
- ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
387
- bsz, _, _ = hidden_states.size()
388
- if encoder_hidden_states is not None:
389
- if not hasattr(self, "q_attn"):
390
- raise ValueError(
391
- "If class is used as cross attention, the weights `q_attn` have to be defined. "
392
- "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
393
- )
394
-
395
- query = self.q_attn(hidden_states)
396
- key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
397
- attention_mask = encoder_attention_mask
398
- else:
399
- query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
400
-
401
- query = self._split_heads(query, self.num_heads, self.head_dim)
402
- key = self._split_heads(key, self.num_heads, self.head_dim)
403
- value = self._split_heads(value, self.num_heads, self.head_dim)
404
-
405
- if layer_past is not None:
406
- past_key = layer_past[0]
407
- past_value = layer_past[1]
408
- key = torch.cat((past_key, key), dim=-2)
409
- value = torch.cat((past_value, value), dim=-2)
410
-
411
- present = None
412
- if use_cache is True:
413
- present = (key, value)
414
-
415
- query_length = query.shape[2]
416
- tgt_len = key.shape[2]
417
-
418
- # Flash attention requires the input to have the shape
419
- # batch_size x seq_length x head_dim x hidden_dim
420
- query = query.transpose(1, 2).view(bsz, query_length, self.num_heads, self.head_dim)
421
- key = key.transpose(1, 2).view(bsz, tgt_len, self.num_heads, self.head_dim)
422
- value = value.transpose(1, 2).view(bsz, tgt_len, self.num_heads, self.head_dim)
423
-
424
- attn_dropout = self.attn_dropout.p if self.training else 0.0
425
-
426
- # In PEFT, usually we cast the layer norms in float32 for training stability reasons
427
- # therefore the input hidden states gets silently casted in float32. Hence, we need
428
- # cast them back in the correct dtype just to be sure everything works as expected.
429
- # This might slowdown training & inference so it is recommended to not cast the LayerNorms
430
- # in fp32. (LlamaRMSNorm handles it correctly)
431
-
432
- if query.dtype == torch.float32:
433
- if torch.is_autocast_enabled():
434
- target_dtype = torch.get_autocast_gpu_dtype()
435
- # Handle the case where the model is quantized
436
- elif hasattr(self.config, "_pre_quantization_dtype"):
437
- target_dtype = self.config._pre_quantization_dtype
438
- else:
439
- target_dtype = self.c_proj.weight.dtype
440
-
441
- logger.warning_once(
442
- f"The input hidden states seems to be silently casted in float32, this might be related to"
443
- f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
444
- f" {target_dtype}."
445
- )
446
-
447
- query = query.to(target_dtype)
448
- key = key.to(target_dtype)
449
- value = value.to(target_dtype)
450
-
451
- attn_output = self._flash_attention_forward(
452
- query, key, value, attention_mask, query_length, dropout=attn_dropout
453
- )
454
-
455
- attn_weights_reshaped = attn_output.reshape(bsz, query_length, self.num_heads * self.head_dim)
456
- attn_output = self.c_proj(attn_weights_reshaped)
457
- attn_output = self.resid_dropout(attn_output)
458
-
459
- outputs = (attn_output, present)
460
- if output_attentions:
461
- outputs += (attn_weights_reshaped,)
462
-
463
- return outputs
464
-
465
- # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
466
- def _flash_attention_forward(
467
- self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
468
- ):
469
- """
470
- Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
471
- first unpad the input, then computes the attention scores and pad the final attention scores.
472
-
473
- Args:
474
- query_states (`torch.Tensor`):
475
- Input query states to be passed to Flash Attention API
476
- key_states (`torch.Tensor`):
477
- Input key states to be passed to Flash Attention API
478
- value_states (`torch.Tensor`):
479
- Input value states to be passed to Flash Attention API
480
- attention_mask (`torch.Tensor`):
481
- The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
482
- position of padding tokens and 1 for the position of non-padding tokens.
483
- dropout (`float`):
484
- Attention dropout
485
- softmax_scale (`float`, *optional*):
486
- The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
487
- """
488
- if not self._flash_attn_uses_top_left_mask:
489
- causal = self.is_causal
490
- else:
491
- # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
492
- causal = self.is_causal and query_length != 1
493
-
494
- # Contains at least one padding token in the sequence
495
- if attention_mask is not None:
496
- batch_size = query_states.shape[0]
497
- query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
498
- query_states, key_states, value_states, attention_mask, query_length
499
- )
500
-
501
- cu_seqlens_q, cu_seqlens_k = cu_seq_lens
502
- max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
503
-
504
- attn_output_unpad = flash_attn_varlen_func(
505
- query_states,
506
- key_states,
507
- value_states,
508
- cu_seqlens_q=cu_seqlens_q,
509
- cu_seqlens_k=cu_seqlens_k,
510
- max_seqlen_q=max_seqlen_in_batch_q,
511
- max_seqlen_k=max_seqlen_in_batch_k,
512
- dropout_p=dropout,
513
- softmax_scale=softmax_scale,
514
- causal=causal,
515
- )
516
-
517
- attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
518
- else:
519
- attn_output = flash_attn_func(
520
- query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
521
- )
522
-
523
- return attn_output
524
-
525
- # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
526
- def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
527
- indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
528
- batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
529
-
530
- key_layer = index_first_axis(
531
- key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
532
- )
533
- value_layer = index_first_axis(
534
- value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
535
- )
536
- if query_length == kv_seq_len:
537
- query_layer = index_first_axis(
538
- query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
539
- )
540
- cu_seqlens_q = cu_seqlens_k
541
- max_seqlen_in_batch_q = max_seqlen_in_batch_k
542
- indices_q = indices_k
543
- elif query_length == 1:
544
- max_seqlen_in_batch_q = 1
545
- cu_seqlens_q = torch.arange(
546
- batch_size + 1, dtype=torch.int32, device=query_layer.device
547
- ) # There is a memcpy here, that is very bad.
548
- indices_q = cu_seqlens_q[:-1]
549
- query_layer = query_layer.squeeze(1)
550
- else:
551
- # The -q_len: slice assumes left padding.
552
- attention_mask = attention_mask[:, -query_length:]
553
- query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
554
-
555
- return (
556
- query_layer,
557
- key_layer,
558
- value_layer,
559
- indices_q,
560
- (cu_seqlens_q, cu_seqlens_k),
561
- (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
562
- )
563
-
564
-
565
- class GPT2MLP(nn.Module):
566
- def __init__(self, intermediate_size, config):
567
- super().__init__()
568
- embed_dim = config.hidden_size
569
- self.c_fc = Conv1D(intermediate_size, embed_dim)
570
- self.c_proj = Conv1D(embed_dim, intermediate_size)
571
- self.act = ACT2FN[config.activation_function]
572
- self.dropout = nn.Dropout(config.resid_pdrop)
573
-
574
- def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
575
- hidden_states = self.c_fc(hidden_states)
576
- hidden_states = self.act(hidden_states)
577
- hidden_states = self.c_proj(hidden_states)
578
- hidden_states = self.dropout(hidden_states)
579
- return hidden_states
580
-
581
-
582
- GPT2_ATTENTION_CLASSES = {
583
- "eager": GPT2Attention,
584
- "flash_attention_2": GPT2FlashAttention2,
585
- }
586
-
587
-
588
- class GPT2Block(nn.Module):
589
- def __init__(self, config, layer_idx=None):
590
- super().__init__()
591
- hidden_size = config.hidden_size
592
- inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
593
- attention_class = GPT2_ATTENTION_CLASSES[config._attn_implementation]
594
-
595
- self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
596
- self.attn = attention_class(config=config, layer_idx=layer_idx)
597
- self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
598
-
599
- if config.add_cross_attention:
600
- self.crossattention = attention_class(config=config, is_cross_attention=True, layer_idx=layer_idx)
601
- self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
602
-
603
- self.mlp = GPT2MLP(inner_dim, config)
604
-
605
- def forward(
606
- self,
607
- hidden_states: Optional[Tuple[torch.FloatTensor]],
608
- layer_past: Optional[Tuple[torch.Tensor]] = None,
609
- attention_mask: Optional[torch.FloatTensor] = None,
610
- head_mask: Optional[torch.FloatTensor] = None,
611
- encoder_hidden_states: Optional[torch.Tensor] = None,
612
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
613
- use_cache: Optional[bool] = False,
614
- output_attentions: Optional[bool] = False,
615
- ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
616
- residual = hidden_states
617
- hidden_states = self.ln_1(hidden_states)
618
- attn_outputs = self.attn(
619
- hidden_states,
620
- layer_past=layer_past,
621
- attention_mask=attention_mask,
622
- head_mask=head_mask,
623
- use_cache=use_cache,
624
- output_attentions=output_attentions,
625
- )
626
- attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
627
- outputs = attn_outputs[1:]
628
- # residual connection
629
- hidden_states = attn_output + residual
630
-
631
- if encoder_hidden_states is not None:
632
- # add one self-attention block for cross-attention
633
- if not hasattr(self, "crossattention"):
634
- raise ValueError(
635
- f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
636
- "cross-attention layers by setting `config.add_cross_attention=True`"
637
- )
638
- residual = hidden_states
639
- hidden_states = self.ln_cross_attn(hidden_states)
640
- cross_attn_outputs = self.crossattention(
641
- hidden_states,
642
- attention_mask=attention_mask,
643
- head_mask=head_mask,
644
- encoder_hidden_states=encoder_hidden_states,
645
- encoder_attention_mask=encoder_attention_mask,
646
- output_attentions=output_attentions,
647
- )
648
- attn_output = cross_attn_outputs[0]
649
- # residual connection
650
- hidden_states = residual + attn_output
651
- outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
652
-
653
- residual = hidden_states
654
- hidden_states = self.ln_2(hidden_states)
655
- feed_forward_hidden_states = self.mlp(hidden_states)
656
- # residual connection
657
- hidden_states = residual + feed_forward_hidden_states
658
-
659
- if use_cache:
660
- outputs = (hidden_states,) + outputs
661
- else:
662
- outputs = (hidden_states,) + outputs[1:]
663
-
664
- return outputs # hidden_states, present, (attentions, cross_attentions)
665
-
666
-
667
- class GPT2PreTrainedModel(PreTrainedModel):
668
- """
669
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
670
- models.
671
- """
672
-
673
- config_class = GPT2Config
674
- load_tf_weights = load_tf_weights_in_gpt2
675
- base_model_prefix = "transformer"
676
- is_parallelizable = True
677
- supports_gradient_checkpointing = True
678
- _no_split_modules = ["GPT2Block"]
679
- _skip_keys_device_placement = "past_key_values"
680
- _supports_flash_attn_2 = True
681
-
682
- def __init__(self, *inputs, **kwargs):
683
- super().__init__(*inputs, **kwargs)
684
-
685
- def _init_weights(self, module):
686
- """Initialize the weights."""
687
- if isinstance(module, (nn.Linear, Conv1D)):
688
- # Slightly different from the TF version which uses truncated_normal for initialization
689
- # cf https://github.com/pytorch/pytorch/pull/5617
690
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
691
- if module.bias is not None:
692
- module.bias.data.zero_()
693
- elif isinstance(module, nn.Embedding):
694
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
695
- if module.padding_idx is not None:
696
- module.weight.data[module.padding_idx].zero_()
697
- elif isinstance(module, nn.LayerNorm):
698
- module.bias.data.zero_()
699
- module.weight.data.fill_(1.0)
700
-
701
- # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
702
- # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
703
- # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
704
- # > -- GPT-2 :: https://openai.com/blog/better-language-models/
705
- #
706
- # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
707
- for name, p in module.named_parameters():
708
- if name == "c_proj.weight":
709
- # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
710
- p.data.normal_(mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer)))
711
-
712
-
713
- @dataclass
714
- class GPT2DoubleHeadsModelOutput(ModelOutput):
715
- """
716
- Base class for outputs of models predicting if two sentences are consecutive or not.
717
-
718
- Args:
719
- loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
720
- Language modeling loss.
721
- mc_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mc_labels` is provided):
722
- Multiple choice classification loss.
723
- logits (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`):
724
- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
725
- mc_logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
726
- Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
727
- past_key_values (`Tuple[Tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
728
- Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
729
- sequence_length, embed_size_per_head)`).
730
-
731
- Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
732
- `past_key_values` input) to speed up sequential decoding.
733
- hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
734
- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
735
- shape `(batch_size, sequence_length, hidden_size)`.
736
-
737
- Hidden-states of the model at the output of each layer plus the initial embedding outputs.
738
- attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
739
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
740
- sequence_length)`.
741
-
742
- GPT2Attentions weights after the attention softmax, used to compute the weighted average in the
743
- self-attention heads.
744
- """
745
-
746
- loss: Optional[torch.FloatTensor] = None
747
- mc_loss: Optional[torch.FloatTensor] = None
748
- logits: torch.FloatTensor = None
749
- mc_logits: torch.FloatTensor = None
750
- past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
751
- hidden_states: Optional[Tuple[torch.FloatTensor]] = None
752
- attentions: Optional[Tuple[torch.FloatTensor]] = None
753
-
754
-
755
- GPT2_START_DOCSTRING = r"""
756
-
757
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
758
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
759
- etc.)
760
-
761
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
762
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
763
- and behavior.
764
-
765
- Parameters:
766
- config ([`GPT2Config`]): Model configuration class with all the parameters of the model.
767
- Initializing with a config file does not load the weights associated with the model, only the
768
- configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
769
- """
770
-
771
- GPT2_INPUTS_DOCSTRING = r"""
772
- Args:
773
- input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
774
- `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
775
- `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
776
- sequence tokens in the vocabulary.
777
-
778
- If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
779
- `input_ids`.
780
-
781
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
782
- [`PreTrainedTokenizer.__call__`] for details.
783
-
784
- [What are input IDs?](../glossary#input-ids)
785
- past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
786
- Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
787
- `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
788
- their past given to this model should not be passed as `input_ids` as they have already been computed.
789
- attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
790
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
791
-
792
- - 1 for tokens that are **not masked**,
793
- - 0 for tokens that are **masked**.
794
-
795
- If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
796
- `past_key_values`. In other words, the `attention_mask` always has to have the length:
797
- `len(past_key_values) + len(input_ids)`
798
-
799
- [What are attention masks?](../glossary#attention-mask)
800
- token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
801
- Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
802
- 1]`:
803
-
804
- - 0 corresponds to a *sentence A* token,
805
- - 1 corresponds to a *sentence B* token.
806
-
807
- [What are token type IDs?](../glossary#token-type-ids)
808
- position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
809
- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
810
- config.max_position_embeddings - 1]`.
811
-
812
- [What are position IDs?](../glossary#position-ids)
813
- head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
814
- Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
815
-
816
- - 1 indicates the head is **not masked**,
817
- - 0 indicates the head is **masked**.
818
-
819
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
820
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
821
- is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
822
- model's internal embedding lookup matrix.
823
-
824
- If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
825
- `past_key_values`).
826
- use_cache (`bool`, *optional*):
827
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
828
- `past_key_values`).
829
- output_attentions (`bool`, *optional*):
830
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
831
- tensors for more detail.
832
- output_hidden_states (`bool`, *optional*):
833
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
834
- more detail.
835
- return_dict (`bool`, *optional*):
836
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
837
- """
838
- PARALLELIZE_DOCSTRING = r"""
839
- This is an experimental feature and is a subject to change at a moment's notice.
840
-
841
- Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
842
- it will evenly distribute blocks across all devices.
843
-
844
- Args:
845
- device_map (`Dict[int, list]`, optional, defaults to None):
846
- A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
847
- automatically mapped to the first device (for esoteric reasons). That means that the first device should
848
- have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
849
- following number of attention modules:
850
-
851
- - openai-community/gpt2: 12
852
- - openai-community/gpt2-medium: 24
853
- - openai-community/gpt2-large: 36
854
- - openai-community/gpt2-xl: 48
855
-
856
- Example:
857
-
858
- ```python
859
- # Here is an example of a device map on a machine with 4 GPUs using gpt2-xl, which has a total of 48 attention modules:
860
- model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2-xl")
861
- device_map = {
862
- 0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
863
- 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
864
- 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
865
- 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
866
- }
867
- model.parallelize(device_map)
868
- ```
869
- """
870
- DEPARALLELIZE_DOCSTRING = r"""
871
- Moves the model to cpu from a model parallel state.
872
-
873
- Example:
874
-
875
- ```python
876
- # On a 4 GPU machine with openai-community/gpt2-large:
877
- model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2-large")
878
- device_map = {
879
- 0: [0, 1, 2, 3, 4, 5, 6, 7],
880
- 1: [8, 9, 10, 11, 12, 13, 14, 15],
881
- 2: [16, 17, 18, 19, 20, 21, 22, 23],
882
- 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
883
- }
884
- model.parallelize(device_map) # Splits the model across several devices
885
- model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
886
- ```
887
- """
888
-
889
-
890
- @add_start_docstrings(
891
- "The bare GPT2 Model transformer outputting raw hidden-states without any specific head on top.",
892
- GPT2_START_DOCSTRING,
893
- )
894
- class GPT2Model(GPT2PreTrainedModel):
895
- def __init__(self, config):
896
- super().__init__(config)
897
-
898
- self.embed_dim = config.hidden_size
899
-
900
- self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
901
- self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
902
-
903
- self.drop = nn.Dropout(config.embd_pdrop)
904
- self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)])
905
- self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
906
-
907
- # Model parallel
908
- self.model_parallel = False
909
- self.device_map = None
910
- self.gradient_checkpointing = False
911
- self._attn_implementation = config._attn_implementation
912
-
913
- # Initialize weights and apply final processing
914
- self.post_init()
915
-
916
- @add_start_docstrings(PARALLELIZE_DOCSTRING)
917
- def parallelize(self, device_map=None):
918
- # Check validity of device_map
919
- warnings.warn(
920
- "`GPT2Model.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
921
- " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
922
- " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
923
- " ...}",
924
- FutureWarning,
925
- )
926
- self.device_map = (
927
- get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
928
- )
929
- assert_device_map(self.device_map, len(self.h))
930
- self.model_parallel = True
931
- self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
932
- self.last_device = "cuda:" + str(max(self.device_map.keys()))
933
- self.wte = self.wte.to(self.first_device)
934
- self.wpe = self.wpe.to(self.first_device)
935
- # Load onto devices
936
- for k, v in self.device_map.items():
937
- for block in v:
938
- cuda_device = "cuda:" + str(k)
939
- self.h[block] = self.h[block].to(cuda_device)
940
- # ln_f to last
941
- self.ln_f = self.ln_f.to(self.last_device)
942
-
943
- @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
944
- def deparallelize(self):
945
- warnings.warn(
946
- "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
947
- FutureWarning,
948
- )
949
- self.model_parallel = False
950
- self.device_map = None
951
- self.first_device = "cpu"
952
- self.last_device = "cpu"
953
- self.wte = self.wte.to("cpu")
954
- self.wpe = self.wpe.to("cpu")
955
- for index in range(len(self.h)):
956
- self.h[index] = self.h[index].to("cpu")
957
- self.ln_f = self.ln_f.to("cpu")
958
- torch.cuda.empty_cache()
959
-
960
- def get_input_embeddings(self):
961
- return self.wte
962
-
963
- def set_input_embeddings(self, new_embeddings):
964
- self.wte = new_embeddings
965
-
966
- def _prune_heads(self, heads_to_prune):
967
- """
968
- Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
969
- """
970
- for layer, heads in heads_to_prune.items():
971
- self.h[layer].attn.prune_heads(heads)
972
-
973
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
974
- @add_code_sample_docstrings(
975
- checkpoint=_CHECKPOINT_FOR_DOC,
976
- output_type=BaseModelOutputWithPastAndCrossAttentions,
977
- config_class=_CONFIG_FOR_DOC,
978
- )
979
- def forward(
980
- self,
981
- input_ids: Optional[torch.LongTensor] = None,
982
- past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
983
- attention_mask: Optional[torch.FloatTensor] = None,
984
- token_type_ids: Optional[torch.LongTensor] = None,
985
- position_ids: Optional[torch.LongTensor] = None,
986
- head_mask: Optional[torch.FloatTensor] = None,
987
- inputs_embeds: Optional[torch.FloatTensor] = None,
988
- encoder_hidden_states: Optional[torch.Tensor] = None,
989
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
990
- use_cache: Optional[bool] = None,
991
- output_attentions: Optional[bool] = None,
992
- output_hidden_states: Optional[bool] = None,
993
- return_dict: Optional[bool] = None,
994
- ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
995
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
996
- output_hidden_states = (
997
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
998
- )
999
- use_cache = use_cache if use_cache is not None else self.config.use_cache
1000
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1001
-
1002
- if input_ids is not None and inputs_embeds is not None:
1003
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1004
- elif input_ids is not None:
1005
- self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1006
- input_shape = input_ids.size()
1007
- input_ids = input_ids.view(-1, input_shape[-1])
1008
- batch_size = input_ids.shape[0]
1009
- elif inputs_embeds is not None:
1010
- input_shape = inputs_embeds.size()[:-1]
1011
- batch_size = inputs_embeds.shape[0]
1012
- else:
1013
- raise ValueError("You have to specify either input_ids or inputs_embeds")
1014
-
1015
- device = input_ids.device if input_ids is not None else inputs_embeds.device
1016
-
1017
- if token_type_ids is not None:
1018
- token_type_ids = token_type_ids.view(-1, input_shape[-1])
1019
-
1020
- if past_key_values is None:
1021
- past_length = 0
1022
- past_key_values = tuple([None] * len(self.h))
1023
- else:
1024
- past_length = past_key_values[0][0].size(-2)
1025
- if position_ids is None:
1026
- position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
1027
- position_ids = position_ids.unsqueeze(0)
1028
-
1029
- # Attention mask.
1030
- if attention_mask is not None:
1031
- attention_mask = attention_mask.view(batch_size, -1)
1032
- if self._attn_implementation == "flash_attention_2":
1033
- attention_mask = attention_mask if 0 in attention_mask else None
1034
- else:
1035
- # We create a 3D attention mask from a 2D tensor mask.
1036
- # Sizes are [batch_size, 1, 1, to_seq_length]
1037
- # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
1038
- # this attention mask is more simple than the triangular masking of causal attention
1039
- # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
1040
- attention_mask = attention_mask[:, None, None, :]
1041
-
1042
- # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
1043
- # masked positions, this operation will create a tensor which is 0.0 for
1044
- # positions we want to attend and the dtype's smallest value for masked positions.
1045
- # Since we are adding it to the raw scores before the softmax, this is
1046
- # effectively the same as removing these entirely.
1047
- attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
1048
- attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
1049
-
1050
- # If a 2D or 3D attention mask is provided for the cross-attention
1051
- # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1052
- if self.config.add_cross_attention and encoder_hidden_states is not None:
1053
- encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
1054
- encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1055
- if encoder_attention_mask is None:
1056
- encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
1057
- if self._attn_implementation != "flash_attention_2":
1058
- encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
1059
- else:
1060
- encoder_attention_mask = None
1061
-
1062
- # Prepare head mask if needed
1063
- # 1.0 in head_mask indicate we keep the head
1064
- # attention_probs has shape bsz x n_heads x N x N
1065
- # head_mask has shape n_layer x batch x n_heads x N x N
1066
- head_mask = self.get_head_mask(head_mask, self.config.n_layer)
1067
-
1068
- if inputs_embeds is None:
1069
- inputs_embeds = self.wte(input_ids)
1070
- position_embeds = self.wpe(position_ids)
1071
- hidden_states = inputs_embeds + position_embeds
1072
-
1073
- if token_type_ids is not None:
1074
- token_type_embeds = self.wte(token_type_ids)
1075
- hidden_states = hidden_states + token_type_embeds
1076
-
1077
- hidden_states = self.drop(hidden_states)
1078
-
1079
- output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),)
1080
-
1081
- if self.gradient_checkpointing and self.training:
1082
- if use_cache:
1083
- logger.warning_once(
1084
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1085
- )
1086
- use_cache = False
1087
-
1088
- presents = () if use_cache else None
1089
- all_self_attentions = () if output_attentions else None
1090
- all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
1091
- all_hidden_states = () if output_hidden_states else None
1092
- for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
1093
- # Model parallel
1094
- if self.model_parallel:
1095
- torch.cuda.set_device(hidden_states.device)
1096
- # Ensure layer_past is on same device as hidden_states (might not be correct)
1097
- if layer_past is not None:
1098
- layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
1099
- # Ensure that attention_mask is always on the same device as hidden_states
1100
- if attention_mask is not None:
1101
- attention_mask = attention_mask.to(hidden_states.device)
1102
- if isinstance(head_mask, torch.Tensor):
1103
- head_mask = head_mask.to(hidden_states.device)
1104
- if output_hidden_states:
1105
- all_hidden_states = all_hidden_states + (hidden_states,)
1106
-
1107
- if self.gradient_checkpointing and self.training:
1108
- outputs = self._gradient_checkpointing_func(
1109
- block.__call__,
1110
- hidden_states,
1111
- None,
1112
- attention_mask,
1113
- head_mask[i],
1114
- encoder_hidden_states,
1115
- encoder_attention_mask,
1116
- use_cache,
1117
- output_attentions,
1118
- )
1119
- else:
1120
- outputs = block(
1121
- hidden_states,
1122
- layer_past=layer_past,
1123
- attention_mask=attention_mask,
1124
- head_mask=head_mask[i],
1125
- encoder_hidden_states=encoder_hidden_states,
1126
- encoder_attention_mask=encoder_attention_mask,
1127
- use_cache=use_cache,
1128
- output_attentions=output_attentions,
1129
- )
1130
-
1131
- hidden_states = outputs[0]
1132
- if use_cache is True:
1133
- presents = presents + (outputs[1],)
1134
-
1135
- if output_attentions:
1136
- all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
1137
- if self.config.add_cross_attention:
1138
- all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
1139
-
1140
- # Model Parallel: If it's the last layer for that device, put things on the next device
1141
- if self.model_parallel:
1142
- for k, v in self.device_map.items():
1143
- if i == v[-1] and "cuda:" + str(k) != self.last_device:
1144
- hidden_states = hidden_states.to("cuda:" + str(k + 1))
1145
-
1146
- hidden_states = self.ln_f(hidden_states)
1147
-
1148
- hidden_states = hidden_states.view(output_shape)
1149
- # Add last hidden state
1150
- if output_hidden_states:
1151
- all_hidden_states = all_hidden_states + (hidden_states,)
1152
-
1153
- if not return_dict:
1154
- return tuple(
1155
- v
1156
- for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
1157
- if v is not None
1158
- )
1159
-
1160
- return BaseModelOutputWithPastAndCrossAttentions(
1161
- last_hidden_state=hidden_states,
1162
- past_key_values=presents,
1163
- hidden_states=all_hidden_states,
1164
- attentions=all_self_attentions,
1165
- cross_attentions=all_cross_attentions,
1166
- )
1167
-
1168
-
1169
- @add_start_docstrings(
1170
- """
1171
- The GPT2 Model transformer with a language modeling head on top (linear layer with weights tied to the input
1172
- embeddings).
1173
- """,
1174
- GPT2_START_DOCSTRING,
1175
- )
1176
- class GPT2LMHeadModel(GPT2PreTrainedModel):
1177
- _tied_weights_keys = ["lm_head.weight"]
1178
-
1179
- def __init__(self, config):
1180
- super().__init__(config)
1181
- self.transformer = GPT2Model(config)
1182
- self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1183
-
1184
- # Model parallel
1185
- self.model_parallel = False
1186
- self.device_map = None
1187
-
1188
- # Initialize weights and apply final processing
1189
- self.post_init()
1190
-
1191
- @add_start_docstrings(PARALLELIZE_DOCSTRING)
1192
- def parallelize(self, device_map=None):
1193
- warnings.warn(
1194
- "`GPT2LMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
1195
- " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
1196
- " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
1197
- " 0, 'transformer.h.1': 1, ...}",
1198
- FutureWarning,
1199
- )
1200
- self.device_map = (
1201
- get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1202
- if device_map is None
1203
- else device_map
1204
- )
1205
- assert_device_map(self.device_map, len(self.transformer.h))
1206
- self.transformer.parallelize(self.device_map)
1207
- self.lm_head = self.lm_head.to(self.transformer.first_device)
1208
- self.model_parallel = True
1209
-
1210
- @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1211
- def deparallelize(self):
1212
- warnings.warn(
1213
- "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1214
- FutureWarning,
1215
- )
1216
- self.transformer.deparallelize()
1217
- self.transformer = self.transformer.to("cpu")
1218
- self.lm_head = self.lm_head.to("cpu")
1219
- self.model_parallel = False
1220
- torch.cuda.empty_cache()
1221
-
1222
- def get_output_embeddings(self):
1223
- return self.lm_head
1224
-
1225
- def set_output_embeddings(self, new_embeddings):
1226
- self.lm_head = new_embeddings
1227
-
1228
- def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1229
- token_type_ids = kwargs.get("token_type_ids", None)
1230
- # Omit tokens covered by past_key_values
1231
- if past_key_values:
1232
- past_length = past_key_values[0][0].shape[2]
1233
-
1234
- # Some generation methods already pass only the last input ID
1235
- if input_ids.shape[1] > past_length:
1236
- remove_prefix_length = past_length
1237
- else:
1238
- # Default to old behavior: keep only final ID
1239
- remove_prefix_length = input_ids.shape[1] - 1
1240
-
1241
- input_ids = input_ids[:, remove_prefix_length:]
1242
- if token_type_ids is not None:
1243
- token_type_ids = token_type_ids[:, -input_ids.shape[1] :]
1244
-
1245
- attention_mask = kwargs.get("attention_mask", None)
1246
- position_ids = kwargs.get("position_ids", None)
1247
-
1248
- if attention_mask is not None and position_ids is None:
1249
- # create position_ids on the fly for batch generation
1250
- position_ids = attention_mask.long().cumsum(-1) - 1
1251
- position_ids.masked_fill_(attention_mask == 0, 1)
1252
- if past_key_values:
1253
- position_ids = position_ids[:, -input_ids.shape[1] :]
1254
- else:
1255
- position_ids = None
1256
-
1257
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1258
- if inputs_embeds is not None and past_key_values is None:
1259
- model_inputs = {"inputs_embeds": inputs_embeds}
1260
- else:
1261
- model_inputs = {"input_ids": input_ids}
1262
-
1263
- model_inputs.update(
1264
- {
1265
- "past_key_values": past_key_values,
1266
- "use_cache": kwargs.get("use_cache"),
1267
- "position_ids": position_ids,
1268
- "attention_mask": attention_mask,
1269
- "token_type_ids": token_type_ids,
1270
- }
1271
- )
1272
-
1273
- return model_inputs
1274
-
1275
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1276
- @add_code_sample_docstrings(
1277
- checkpoint=_CHECKPOINT_FOR_DOC,
1278
- output_type=CausalLMOutputWithCrossAttentions,
1279
- config_class=_CONFIG_FOR_DOC,
1280
- )
1281
- def forward(
1282
- self,
1283
- input_ids: Optional[torch.LongTensor] = None,
1284
- past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1285
- attention_mask: Optional[torch.FloatTensor] = None,
1286
- token_type_ids: Optional[torch.LongTensor] = None,
1287
- position_ids: Optional[torch.LongTensor] = None,
1288
- head_mask: Optional[torch.FloatTensor] = None,
1289
- inputs_embeds: Optional[torch.FloatTensor] = None,
1290
- encoder_hidden_states: Optional[torch.Tensor] = None,
1291
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
1292
- labels: Optional[torch.LongTensor] = None,
1293
- use_cache: Optional[bool] = None,
1294
- output_attentions: Optional[bool] = None,
1295
- output_hidden_states: Optional[bool] = None,
1296
- return_dict: Optional[bool] = None,
1297
- ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1298
- r"""
1299
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1300
- Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1301
- `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1302
- are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1303
- """
1304
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1305
-
1306
- transformer_outputs = self.transformer(
1307
- input_ids,
1308
- past_key_values=past_key_values,
1309
- attention_mask=attention_mask,
1310
- token_type_ids=token_type_ids,
1311
- position_ids=position_ids,
1312
- head_mask=head_mask,
1313
- inputs_embeds=inputs_embeds,
1314
- encoder_hidden_states=encoder_hidden_states,
1315
- encoder_attention_mask=encoder_attention_mask,
1316
- use_cache=use_cache,
1317
- output_attentions=output_attentions,
1318
- output_hidden_states=output_hidden_states,
1319
- return_dict=return_dict,
1320
- )
1321
- hidden_states = transformer_outputs[0]
1322
-
1323
- # Set device for model parallelism
1324
- if self.model_parallel:
1325
- torch.cuda.set_device(self.transformer.first_device)
1326
- hidden_states = hidden_states.to(self.lm_head.weight.device)
1327
-
1328
- lm_logits = self.lm_head(hidden_states)
1329
-
1330
- loss = None
1331
- if labels is not None:
1332
- # move labels to correct device to enable model parallelism
1333
- labels = labels.to(lm_logits.device)
1334
- # Shift so that tokens < n predict n
1335
- shift_logits = lm_logits[..., :-1, :].contiguous()
1336
- shift_labels = labels[..., 1:].contiguous()
1337
- # Flatten the tokens
1338
- loss_fct = CrossEntropyLoss()
1339
- loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1340
-
1341
- if not return_dict:
1342
- output = (lm_logits,) + transformer_outputs[1:]
1343
- return ((loss,) + output) if loss is not None else output
1344
-
1345
- return CausalLMOutputWithCrossAttentions(
1346
- loss=loss,
1347
- logits=lm_logits,
1348
- past_key_values=transformer_outputs.past_key_values,
1349
- hidden_states=transformer_outputs.hidden_states,
1350
- attentions=transformer_outputs.attentions,
1351
- cross_attentions=transformer_outputs.cross_attentions,
1352
- )
1353
-
1354
- @staticmethod
1355
- def _reorder_cache(
1356
- past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1357
- ) -> Tuple[Tuple[torch.Tensor]]:
1358
- """
1359
- This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1360
- [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1361
- beam_idx at every generation step.
1362
- """
1363
- return tuple(
1364
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1365
- for layer_past in past_key_values
1366
- )
1367
-
1368
-
1369
- @add_start_docstrings(
1370
- """
1371
- The GPT2 Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
1372
- RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
1373
- input embeddings, the classification head takes as input the input of a specified classification token index in the
1374
- input sequence).
1375
- """,
1376
- GPT2_START_DOCSTRING,
1377
- )
1378
- class GPT2DoubleHeadsModel(GPT2PreTrainedModel):
1379
- _tied_weights_keys = ["lm_head.weight"]
1380
-
1381
- def __init__(self, config):
1382
- super().__init__(config)
1383
- config.num_labels = 1
1384
- self.transformer = GPT2Model(config)
1385
- self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1386
- self.multiple_choice_head = SequenceSummary(config)
1387
-
1388
- # Model parallel
1389
- self.model_parallel = False
1390
- self.device_map = None
1391
-
1392
- # Initialize weights and apply final processing
1393
- self.post_init()
1394
-
1395
- @add_start_docstrings(PARALLELIZE_DOCSTRING)
1396
- def parallelize(self, device_map=None):
1397
- warnings.warn(
1398
- "`GPT2DoubleHeadsModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should"
1399
- " load your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your"
1400
- " own `device_map` but it needs to be a dictionary module_name to device, so for instance"
1401
- " {'transformer.h.0': 0, 'transformer.h.1': 1, ...}",
1402
- FutureWarning,
1403
- )
1404
- self.device_map = (
1405
- get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1406
- if device_map is None
1407
- else device_map
1408
- )
1409
- assert_device_map(self.device_map, len(self.transformer.h))
1410
- self.transformer.parallelize(self.device_map)
1411
- self.lm_head = self.lm_head.to(self.transformer.first_device)
1412
- self.multiple_choice_head = self.multiple_choice_head.to(self.transformer.first_device)
1413
- self.model_parallel = True
1414
-
1415
- @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1416
- def deparallelize(self):
1417
- warnings.warn(
1418
- "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1419
- FutureWarning,
1420
- )
1421
- self.transformer.deparallelize()
1422
- self.transformer = self.transformer.to("cpu")
1423
- self.lm_head = self.lm_head.to("cpu")
1424
- self.multiple_choice_head = self.multiple_choice_head.to("cpu")
1425
- self.model_parallel = False
1426
- torch.cuda.empty_cache()
1427
-
1428
- def get_output_embeddings(self):
1429
- return self.lm_head
1430
-
1431
- def set_output_embeddings(self, new_embeddings):
1432
- self.lm_head = new_embeddings
1433
-
1434
- def prepare_inputs_for_generation(self, input_ids, inputs_embeds=None, past_key_values=None, **kwargs):
1435
- token_type_ids = kwargs.get("token_type_ids", None)
1436
- # Omit tokens covered by past_key_values
1437
- if past_key_values:
1438
- past_length = past_key_values[0][0].shape[2]
1439
-
1440
- # Some generation methods already pass only the last input ID
1441
- if input_ids.shape[1] > past_length:
1442
- remove_prefix_length = past_length
1443
- else:
1444
- # Default to old behavior: keep only final ID
1445
- remove_prefix_length = input_ids.shape[1] - 1
1446
-
1447
- input_ids = input_ids[:, remove_prefix_length:]
1448
- if token_type_ids is not None:
1449
- token_type_ids = token_type_ids[:, -input_ids.shape[1] :]
1450
-
1451
- attention_mask = kwargs.get("attention_mask", None)
1452
- position_ids = kwargs.get("position_ids", None)
1453
-
1454
- if attention_mask is not None and position_ids is None:
1455
- # create position_ids on the fly for batch generation
1456
- position_ids = attention_mask.long().cumsum(-1) - 1
1457
- position_ids.masked_fill_(attention_mask == 0, 1)
1458
- if past_key_values:
1459
- position_ids = position_ids[:, -input_ids.shape[1] :]
1460
- else:
1461
- position_ids = None
1462
-
1463
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1464
- if inputs_embeds is not None and past_key_values is None:
1465
- model_inputs = {"inputs_embeds": inputs_embeds}
1466
- else:
1467
- model_inputs = {"input_ids": input_ids.contiguous()}
1468
-
1469
- model_inputs.update(
1470
- {
1471
- "past_key_values": past_key_values,
1472
- "use_cache": kwargs.get("use_cache"),
1473
- "position_ids": position_ids,
1474
- "attention_mask": attention_mask,
1475
- "token_type_ids": token_type_ids,
1476
- }
1477
- )
1478
- return model_inputs
1479
-
1480
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1481
- @replace_return_docstrings(output_type=GPT2DoubleHeadsModelOutput, config_class=_CONFIG_FOR_DOC)
1482
- def forward(
1483
- self,
1484
- input_ids: Optional[torch.LongTensor] = None,
1485
- past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1486
- attention_mask: Optional[torch.FloatTensor] = None,
1487
- token_type_ids: Optional[torch.LongTensor] = None,
1488
- position_ids: Optional[torch.LongTensor] = None,
1489
- head_mask: Optional[torch.FloatTensor] = None,
1490
- inputs_embeds: Optional[torch.FloatTensor] = None,
1491
- mc_token_ids: Optional[torch.LongTensor] = None,
1492
- labels: Optional[torch.LongTensor] = None,
1493
- mc_labels: Optional[torch.LongTensor] = None,
1494
- use_cache: Optional[bool] = None,
1495
- output_attentions: Optional[bool] = None,
1496
- output_hidden_states: Optional[bool] = None,
1497
- return_dict: Optional[bool] = None,
1498
- **kwargs,
1499
- ) -> Union[Tuple, GPT2DoubleHeadsModelOutput]:
1500
- r"""
1501
- mc_token_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input):
1502
- Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
1503
- 1]`.
1504
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1505
- Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1506
- `labels = input_ids`. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`. All labels set to
1507
- `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size - 1]`
1508
- mc_labels (`torch.LongTensor` of shape `(batch_size)`, *optional*):
1509
- Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1510
- where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
1511
-
1512
- Return:
1513
-
1514
- Example:
1515
-
1516
- ```python
1517
- >>> import torch
1518
- >>> from transformers import AutoTokenizer, GPT2DoubleHeadsModel
1519
-
1520
- >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
1521
- >>> model = GPT2DoubleHeadsModel.from_pretrained("openai-community/gpt2")
1522
-
1523
- >>> # Add a [CLS] to the vocabulary (we should train it also!)
1524
- >>> num_added_tokens = tokenizer.add_special_tokens({"cls_token": "[CLS]"})
1525
- >>> # Update the model embeddings with the new vocabulary size
1526
- >>> embedding_layer = model.resize_token_embeddings(len(tokenizer))
1527
-
1528
- >>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
1529
- >>> encoded_choices = [tokenizer.encode(s) for s in choices]
1530
- >>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]
1531
-
1532
- >>> input_ids = torch.tensor(encoded_choices).unsqueeze(0) # Batch size: 1, number of choices: 2
1533
- >>> mc_token_ids = torch.tensor([cls_token_location]) # Batch size: 1
1534
-
1535
- >>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
1536
- >>> lm_logits = outputs.logits
1537
- >>> mc_logits = outputs.mc_logits
1538
- ```"""
1539
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1540
-
1541
- transformer_outputs = self.transformer(
1542
- input_ids,
1543
- past_key_values=past_key_values,
1544
- attention_mask=attention_mask,
1545
- token_type_ids=token_type_ids,
1546
- position_ids=position_ids,
1547
- head_mask=head_mask,
1548
- inputs_embeds=inputs_embeds,
1549
- use_cache=use_cache,
1550
- output_attentions=output_attentions,
1551
- output_hidden_states=output_hidden_states,
1552
- return_dict=return_dict,
1553
- )
1554
-
1555
- hidden_states = transformer_outputs[0]
1556
-
1557
- # Set device for model parallelism
1558
- if self.model_parallel:
1559
- torch.cuda.set_device(self.transformer.first_device)
1560
- hidden_states = hidden_states.to(self.lm_head.weight.device)
1561
-
1562
- lm_logits = self.lm_head(hidden_states)
1563
- mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
1564
-
1565
- mc_loss = None
1566
- if mc_labels is not None:
1567
- loss_fct = CrossEntropyLoss()
1568
- mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
1569
- lm_loss = None
1570
- if labels is not None:
1571
- labels = labels.to(lm_logits.device)
1572
- shift_logits = lm_logits[..., :-1, :].contiguous()
1573
- shift_labels = labels[..., 1:].contiguous()
1574
- loss_fct = CrossEntropyLoss()
1575
- lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1576
-
1577
- if not return_dict:
1578
- output = (lm_logits, mc_logits) + transformer_outputs[1:]
1579
- if mc_loss is not None:
1580
- output = (mc_loss,) + output
1581
- return ((lm_loss,) + output) if lm_loss is not None else output
1582
-
1583
- return GPT2DoubleHeadsModelOutput(
1584
- loss=lm_loss,
1585
- mc_loss=mc_loss,
1586
- logits=lm_logits,
1587
- mc_logits=mc_logits,
1588
- past_key_values=transformer_outputs.past_key_values,
1589
- hidden_states=transformer_outputs.hidden_states,
1590
- attentions=transformer_outputs.attentions,
1591
- )
1592
-
1593
- @staticmethod
1594
- def _reorder_cache(
1595
- past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1596
- ) -> Tuple[Tuple[torch.Tensor]]:
1597
- """
1598
- This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1599
- [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1600
- beam_idx at every generation step.
1601
- """
1602
- return tuple(
1603
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1604
- for layer_past in past_key_values
1605
- )
1606
-
1607
-
1608
- @add_start_docstrings(
1609
- """
1610
- The GPT2 Model transformer with a sequence classification head on top (linear layer).
1611
-
1612
- [`GPT2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1613
- (e.g. GPT-1) do.
1614
-
1615
- Since it does classification on the last token, it requires to know the position of the last token. If a
1616
- `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1617
- no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1618
- padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1619
- each row of the batch).
1620
- """,
1621
- GPT2_START_DOCSTRING,
1622
- )
1623
- class GPT2ForSequenceClassification(GPT2PreTrainedModel):
1624
- def __init__(self, config):
1625
- super().__init__(config)
1626
- self.num_labels = config.num_labels
1627
- self.transformer = GPT2Model(config)
1628
- self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1629
-
1630
- # Model parallel
1631
- self.model_parallel = False
1632
- self.device_map = None
1633
-
1634
- # Initialize weights and apply final processing
1635
- self.post_init()
1636
-
1637
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1638
- @add_code_sample_docstrings(
1639
- checkpoint="microsoft/DialogRPT-updown",
1640
- output_type=SequenceClassifierOutputWithPast,
1641
- config_class=_CONFIG_FOR_DOC,
1642
- )
1643
- def forward(
1644
- self,
1645
- input_ids: Optional[torch.LongTensor] = None,
1646
- past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1647
- attention_mask: Optional[torch.FloatTensor] = None,
1648
- token_type_ids: Optional[torch.LongTensor] = None,
1649
- position_ids: Optional[torch.LongTensor] = None,
1650
- head_mask: Optional[torch.FloatTensor] = None,
1651
- inputs_embeds: Optional[torch.FloatTensor] = None,
1652
- labels: Optional[torch.LongTensor] = None,
1653
- use_cache: Optional[bool] = None,
1654
- output_attentions: Optional[bool] = None,
1655
- output_hidden_states: Optional[bool] = None,
1656
- return_dict: Optional[bool] = None,
1657
- ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1658
- r"""
1659
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1660
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1661
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1662
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1663
- """
1664
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1665
-
1666
- transformer_outputs = self.transformer(
1667
- input_ids,
1668
- past_key_values=past_key_values,
1669
- attention_mask=attention_mask,
1670
- token_type_ids=token_type_ids,
1671
- position_ids=position_ids,
1672
- head_mask=head_mask,
1673
- inputs_embeds=inputs_embeds,
1674
- use_cache=use_cache,
1675
- output_attentions=output_attentions,
1676
- output_hidden_states=output_hidden_states,
1677
- return_dict=return_dict,
1678
- )
1679
- hidden_states = transformer_outputs[0]
1680
- logits = self.score(hidden_states)
1681
-
1682
- if input_ids is not None:
1683
- batch_size, sequence_length = input_ids.shape[:2]
1684
- else:
1685
- batch_size, sequence_length = inputs_embeds.shape[:2]
1686
-
1687
- assert (
1688
- self.config.pad_token_id is not None or batch_size == 1
1689
- ), "Cannot handle batch sizes > 1 if no padding token is defined."
1690
- if self.config.pad_token_id is None:
1691
- sequence_lengths = -1
1692
- else:
1693
- if input_ids is not None:
1694
- # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1695
- sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1696
- sequence_lengths = sequence_lengths % input_ids.shape[-1]
1697
- sequence_lengths = sequence_lengths.to(logits.device)
1698
- else:
1699
- sequence_lengths = -1
1700
- logger.warning(
1701
- f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1702
- "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1703
- )
1704
-
1705
- pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1706
-
1707
- loss = None
1708
- if labels is not None:
1709
- if self.config.problem_type is None:
1710
- if self.num_labels == 1:
1711
- self.config.problem_type = "regression"
1712
- elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1713
- self.config.problem_type = "single_label_classification"
1714
- else:
1715
- self.config.problem_type = "multi_label_classification"
1716
-
1717
- if self.config.problem_type == "regression":
1718
- loss_fct = MSELoss()
1719
- if self.num_labels == 1:
1720
- loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1721
- else:
1722
- loss = loss_fct(pooled_logits, labels)
1723
- elif self.config.problem_type == "single_label_classification":
1724
- loss_fct = CrossEntropyLoss()
1725
- loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1726
- elif self.config.problem_type == "multi_label_classification":
1727
- loss_fct = BCEWithLogitsLoss()
1728
- loss = loss_fct(pooled_logits, labels)
1729
- if not return_dict:
1730
- output = (pooled_logits,) + transformer_outputs[1:]
1731
- return ((loss,) + output) if loss is not None else output
1732
-
1733
- return SequenceClassifierOutputWithPast(
1734
- loss=loss,
1735
- logits=pooled_logits,
1736
- past_key_values=transformer_outputs.past_key_values,
1737
- hidden_states=transformer_outputs.hidden_states,
1738
- attentions=transformer_outputs.attentions,
1739
- )
1740
-
1741
-
1742
- @add_start_docstrings(
1743
- """
1744
- GPT2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1745
- Named-Entity-Recognition (NER) tasks.
1746
- """,
1747
- GPT2_START_DOCSTRING,
1748
- )
1749
- class GPT2ForTokenClassification(GPT2PreTrainedModel):
1750
- def __init__(self, config):
1751
- super().__init__(config)
1752
- self.num_labels = config.num_labels
1753
-
1754
- self.transformer = GPT2Model(config)
1755
- if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1756
- classifier_dropout = config.classifier_dropout
1757
- elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1758
- classifier_dropout = config.hidden_dropout
1759
- else:
1760
- classifier_dropout = 0.1
1761
- self.dropout = nn.Dropout(classifier_dropout)
1762
- self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1763
-
1764
- # Model parallel
1765
- self.model_parallel = False
1766
- self.device_map = None
1767
-
1768
- # Initialize weights and apply final processing
1769
- self.post_init()
1770
-
1771
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1772
- # fmt: off
1773
- @add_code_sample_docstrings(
1774
- checkpoint="brad1141/gpt2-finetuned-comp2",
1775
- output_type=TokenClassifierOutput,
1776
- config_class=_CONFIG_FOR_DOC,
1777
- expected_loss=0.25,
1778
- expected_output=[
1779
- "Lead",
1780
- "Lead",
1781
- "Lead",
1782
- "Position",
1783
- "Lead",
1784
- "Lead",
1785
- "Lead",
1786
- "Lead",
1787
- "Lead",
1788
- "Lead",
1789
- "Lead",
1790
- "Lead",
1791
- ],
1792
- )
1793
- # fmt: on
1794
- def forward(
1795
- self,
1796
- input_ids: Optional[torch.LongTensor] = None,
1797
- past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1798
- attention_mask: Optional[torch.FloatTensor] = None,
1799
- token_type_ids: Optional[torch.LongTensor] = None,
1800
- position_ids: Optional[torch.LongTensor] = None,
1801
- head_mask: Optional[torch.FloatTensor] = None,
1802
- inputs_embeds: Optional[torch.FloatTensor] = None,
1803
- labels: Optional[torch.LongTensor] = None,
1804
- use_cache: Optional[bool] = None,
1805
- output_attentions: Optional[bool] = None,
1806
- output_hidden_states: Optional[bool] = None,
1807
- return_dict: Optional[bool] = None,
1808
- ) -> Union[Tuple, TokenClassifierOutput]:
1809
- r"""
1810
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1811
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1812
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1813
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1814
- """
1815
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1816
-
1817
- transformer_outputs = self.transformer(
1818
- input_ids,
1819
- past_key_values=past_key_values,
1820
- attention_mask=attention_mask,
1821
- token_type_ids=token_type_ids,
1822
- position_ids=position_ids,
1823
- head_mask=head_mask,
1824
- inputs_embeds=inputs_embeds,
1825
- use_cache=use_cache,
1826
- output_attentions=output_attentions,
1827
- output_hidden_states=output_hidden_states,
1828
- return_dict=return_dict,
1829
- )
1830
-
1831
- hidden_states = transformer_outputs[0]
1832
- hidden_states = self.dropout(hidden_states)
1833
- logits = self.classifier(hidden_states)
1834
-
1835
- loss = None
1836
- if labels is not None:
1837
- labels = labels.to(logits.device)
1838
- loss_fct = CrossEntropyLoss()
1839
- loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1840
-
1841
- if not return_dict:
1842
- output = (logits,) + transformer_outputs[2:]
1843
- return ((loss,) + output) if loss is not None else output
1844
-
1845
- return TokenClassifierOutput(
1846
- loss=loss,
1847
- logits=logits,
1848
- hidden_states=transformer_outputs.hidden_states,
1849
- attentions=transformer_outputs.attentions,
1850
- )
1851
-
1852
-
1853
- @add_start_docstrings(
1854
- """
1855
- The GPT-2 Model transformer with a span classification head on top for extractive question-answering tasks like
1856
- SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1857
- """,
1858
- GPT2_START_DOCSTRING,
1859
- )
1860
- class GPT2ForQuestionAnswering(GPT2PreTrainedModel):
1861
- def __init__(self, config):
1862
- super().__init__(config)
1863
- self.num_labels = config.num_labels
1864
- self.transformer = GPT2Model(config)
1865
- self.qa_outputs = nn.Linear(config.hidden_size, 2)
1866
-
1867
- # Model parallel
1868
- self.model_parallel = False
1869
- self.device_map = None
1870
-
1871
- # Initialize weights and apply final processing
1872
- self.post_init()
1873
-
1874
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1875
- @add_code_sample_docstrings(
1876
- checkpoint=_CHECKPOINT_FOR_DOC,
1877
- output_type=QuestionAnsweringModelOutput,
1878
- config_class=_CONFIG_FOR_DOC,
1879
- real_checkpoint=_CHECKPOINT_FOR_DOC,
1880
- )
1881
- def forward(
1882
- self,
1883
- input_ids: Optional[torch.LongTensor] = None,
1884
- attention_mask: Optional[torch.FloatTensor] = None,
1885
- token_type_ids: Optional[torch.LongTensor] = None,
1886
- position_ids: Optional[torch.LongTensor] = None,
1887
- head_mask: Optional[torch.FloatTensor] = None,
1888
- inputs_embeds: Optional[torch.FloatTensor] = None,
1889
- start_positions: Optional[torch.LongTensor] = None,
1890
- end_positions: Optional[torch.LongTensor] = None,
1891
- output_attentions: Optional[bool] = None,
1892
- output_hidden_states: Optional[bool] = None,
1893
- return_dict: Optional[bool] = None,
1894
- ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1895
- r"""
1896
- start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1897
- Labels for position (index) of the start of the labelled span for computing the token classification loss.
1898
- Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1899
- are not taken into account for computing the loss.
1900
- end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1901
- Labels for position (index) of the end of the labelled span for computing the token classification loss.
1902
- Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1903
- are not taken into account for computing the loss.
1904
- """
1905
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1906
-
1907
- outputs = self.transformer(
1908
- input_ids,
1909
- attention_mask=attention_mask,
1910
- token_type_ids=token_type_ids,
1911
- position_ids=position_ids,
1912
- head_mask=head_mask,
1913
- inputs_embeds=inputs_embeds,
1914
- output_attentions=output_attentions,
1915
- output_hidden_states=output_hidden_states,
1916
- return_dict=return_dict,
1917
- )
1918
-
1919
- sequence_output = outputs[0]
1920
-
1921
- logits = self.qa_outputs(sequence_output)
1922
- start_logits, end_logits = logits.split(1, dim=-1)
1923
- start_logits = start_logits.squeeze(-1).contiguous()
1924
- end_logits = end_logits.squeeze(-1).contiguous()
1925
-
1926
- total_loss = None
1927
- if start_positions is not None and end_positions is not None:
1928
- # If we are on multi-GPU, split add a dimension
1929
- if len(start_positions.size()) > 1:
1930
- start_positions = start_positions.squeeze(-1).to(start_logits.device)
1931
- if len(end_positions.size()) > 1:
1932
- end_positions = end_positions.squeeze(-1).to(end_logits.device)
1933
- # sometimes the start/end positions are outside our model inputs, we ignore these terms
1934
- ignored_index = start_logits.size(1)
1935
- start_positions = start_positions.clamp(0, ignored_index)
1936
- end_positions = end_positions.clamp(0, ignored_index)
1937
-
1938
- loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1939
- start_loss = loss_fct(start_logits, start_positions)
1940
- end_loss = loss_fct(end_logits, end_positions)
1941
- total_loss = (start_loss + end_loss) / 2
1942
-
1943
- if not return_dict:
1944
- output = (start_logits, end_logits) + outputs[2:]
1945
- return ((total_loss,) + output) if total_loss is not None else output
1946
-
1947
- return QuestionAnsweringModelOutput(
1948
- loss=total_loss,
1949
- start_logits=start_logits,
1950
- end_logits=end_logits,
1951
- hidden_states=outputs.hidden_states,
1952
- attentions=outputs.attentions,
1953
- )
1954
-